REACT-使用styled-components编写CSS
它是通过JavaScript改变CSS编写方式的解决方案之一,从根本上解决常规CSS编写的一些弊端。通过JavaScript来为CSS赋能,我们能达到常规CSS所不好处理的逻辑复杂、函数方法、复用、避免干扰。样式书写将直接依附在JSX上面,HTML、CSS、JS三者再次内聚。all in js的思想。
1. 基本用法
import React, { Component } from 'react'
import styled from 'styled-components'
export default class App extends Component {
render() {
const StyledFooter = styled.footer`
background:pink;
position:fixed;
left:0;
bottom:0;
width:100%;
height:50px;
line-height:50px;
text-align:center;
ul{
display:flex;
padding:0;
margin:0;
li{
flex:1;
list-style:none;
&:hover{
background:green;
}
}
}
`
return (
<div>
<StyledFooter>
<ul>
<li>首页</li>
<li>列表</li>
<li>我的</li>
</ul>
</StyledFooter>
</div>
)
}
}
2. 透传props
import React, { Component } from 'react'
import styled from 'styled-components'
export default class App extends Component {
render() {
const StyledInput = styled.input`
outline:none;
border-radius:10px;
border-bottom:1px solid red;
`
const StyledDiv = styled.div`
background:${props=>props.bg || 'yellow'};
width:200px;
height:200px;
`
return (
<div>
<StyledInput type="text" placeholder="请输入内容"></StyledInput>
<StyledDiv bg="pink"></StyledDiv>
</div>
)
}
}
3. 样式化组件
import React, { Component } from 'react'
import styled from 'styled-components'
export default class App extends Component {
render() {
const StyledChild = styled(Child)`
background:pink;
`
return (
<div>
<StyledChild />
</div>
)
}
}
class Child extends Component{
render(){
return (
<div className={this.props.className}>Child</div>
)
}
}
4. 样式扩展
import React, { Component } from 'react'
import styled from 'styled-components'
export default class App extends Component {
render() {
const StyledButton = styled.button`
width:100px;
height:100px;
background:pink;
`
const StyledButton2 = styled(StyledButton)`
height:50px;
background:blue;
`
const StyledButton3 = styled(StyledButton)`
background:yellow;
`
return (
<div>
<StyledButton></StyledButton>
<StyledButton2></StyledButton2>
<StyledButton3></StyledButton3>
</div>
)
}
}
5. 动画
import React, { Component } from 'react'
import styled, { keyframes } from 'styled-components'
export default class App extends Component {
render() {
const rotateStyle = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
const Rotate = styled.div`
display: inline-block;
animation: ${rotateStyle} 2s linear infinite;
padding: 2rem 1rem;
font-size: 1.2rem;
`;
return (
<div>
<Rotate>旋转</Rotate>
</div>
)
}
}
const Rotate = styled.div`
display: inline-block;
animation: rotateStyle 2s linear infinite;
padding: 2rem 1rem;
font-size: 1.2rem;
@keyframes rotateStyle{
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
`;