styled-components是社区目前最流行的CSS-in-JS库
npm install styled-components
ES6中增加了模板字符串的语法,这个对于很多人来说都会使用。
但是模板字符串还有另外一种用法:标签模板字符串(Tagged Template Literals)。
我们一起来看一个普通的JavaScript的函数:
正常情况下,我们都是通过 函数名() 方式来进行调用的,其实函数还有另外一种调用方式:
如果我们在调用的时候插入其他的变量:
模板字符串被拆分了;
第一个元素是数组,是被模块字符串拆分的字符串组合;
后面的元素是一个个模块字符串传入的内容;
在styled component中,就是通过这种方式来解析模块字符串,最终生成我们想要的样式的
function foo(...args) {console.log(args)
}
foo('hello world')foo`Hello world`const name = 'kobe'
foo`Hello ${name}`
styled-components的本质是通过函数的调用,最终创建出一个组件:
这个组件会被自动添加上一个不重复的class;
styled-components会给该class添加相关的样式;
另外,它支持类似于CSS预处理器一样的样式嵌套:
支持直接子代选择器或后代选择器,并且直接编写样式;
可以通过&符号获取当前元素;
直接伪类选择器、伪元素等;
export const AppWrapper = styled.div`.footer {border: 1px solid orange;}
`
props可以被传递给styled组件
获取props需要通过${}传入一个插值函数,props会作为该函数的参数;
这种方式可以有效的解决动态样式的问题;
import React, { PureComponent } from 'react'
import Home from './home'
import { AppWrapper, SectionWrapper } from "./style"export class App extends PureComponent {constructor() {super()this.state = {size: 30,color: "yellow"}}render() {const { size } = this.statereturn (size}>我是标题
我是内容, 哈哈哈
免责声明
版权声明
)}
}export default App
export const SectionWrapper = styled.div.attrs(props => ({tColor: props.color || "blue"
}))`border: 1px solid red;.title {font-size: ${props => props.size}px;color: ${props => props.tColor};&:hover {background-color: purple;}}.content {font-size: ${largeSize}px;color: ${primaryColor};}
`
支持样式继承
const Button = styled.button`padding: 8px 30px;border-radius: 5px;
`const WarnButton = styled(Button)`background-color: red;color: #fff;
`
styled设置主题
import {ThemeProvider} from 'styled-components'{color: 'red', fontSize: '30px'}}>
const ProfileWrapper = styled.div`color: ${props => props.theme.color};font-size: ${props => props.theme.fontSize}
`
下一篇:法律会纵容“少年恶魔”吗?