是什么
- 通过JavaScript改变CSS编写方式的解决方案之一,从根本上解决常规CSS编写的一些弊端。
- all in js的思想
一、基本写法
import React, { Component } from 'react'
import styled from 'styled-components'
export default class App extends Component {
render() {
const StyledDiv = styled.div`
background: red;
width:100px;
height:100px;
span { // 支持sass写法
color: #FFF;
}
`
return (
<StyledDiv>App
<span>hhh</span>
</StyledDiv>
)
}
}
二、props 穿透
import React, { Component } from 'react'
import styled from 'styled-components'
export default class App extends Component {
render() {
const StyledDiv = styled.div`
background: ${props => props.bg || `yellow`};
width: 100px;
height: 100px;
`
return (
<div>
<StyledDiv bg='blue'></StyledDiv>
</div>
)
}
}
三、样式化扩展
import React, { Component } from 'react'
import styled from 'styled-components'
export default class App extends Component {
render() {
const StyledButton = styled.button`
border-radius: 5px;
background: red;
width: 100px;
height:36px;
border: none;
`
const StyledButton2 = styled(StyledButton)`
background: blue;
`
return (
<div>
<StyledButton>按钮</StyledButton>
<StyledButton2>按钮</StyledButton2>
</div>
)
}
}
四、 动画
import React, { Component } from 'react'
import styled, {keyframes} from 'styled-components'
export default class App extends Component {
render() {
const myanimation = keyframes`
from {
transform:rotate(0deg)
}
to {
transform:rotate(360deg)
}
`
const StyledDiv = styled.div`
width:100px;
height:100px;
background:yellow;
animation: ${myanimation} 1s infinite
`
return (
<StyledDiv>App</StyledDiv>
)
}
}