styled-components 使用小结

1. 常规使用

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #333;        
` 
// 更改了Title的字体颜色, 为红色 const SubTitle = styled(Title)` color: #f00; `

2. 使用props

// 传递props
const SubTitle = styled(Title)<{
    color: string
}>`
  color: ${props => props.color}
`

// 设置默认字体颜色
SubTitle.defaultProps = {
  color: 'green',
}

3. 修改三方组件的样式

import React  from 'react'
import styled, { createGlobalStyle } from 'styled-components'

// 以修改antd ToolTip默认样式为例,  这里是改变字体颜色

const TooltipStyle = createGlobalStyle`
  .ant-tooltip-inner {
    color: #545A69;
  }
`

// 在组件中使用以上样式

const Test = () => {
   return (
      <div>
           <TooltipStyle />   // 使用全局样式
           <Tooltip title= " 我是提示信息" >
             提示
           </Tooltip>
      </div>
    )            
}
    

ps: 为辨别类名, 我们可以在package.json文件 babel中加入styled-components 的插件, 即:

 "babel": {
    "plugins": [
      "babel-plugin-styled-components"
    ]
  },
原文地址:https://www.cnblogs.com/aloehui/p/11005622.html