共计 2146 个字符,预计需要花费 6 分钟才能阅读完成。
npm i styled-components
根本用法
import React, {Component} from 'react'
import styled from 'styled-components'
export default class App extends Component {render() {
const StyledFooter = styled.footer`
background:yellow
`
return (
<StyledFooter>
<footer>
<ul>
<li> 首页 </li>
<li> 列表 </li>
<li> 我的 </li>
</ul>
</footer>
</StyledFooter>
)
}
}
反对 sass/less 语法
import React, {Component} from 'react'
import styled from 'styled-components'
export default class App extends Component {render() {
const StyledFooter = styled.footer`
background:yellow;
position:fixed;
left:0;
bottom:0;
width:100%;
height:50px;
line-height:50px;
text-align:center;
ul{
display:flex;
list-style:none;
li{
flex:1;
&:hover{background:red;}
}
}
`
return (
<StyledFooter>
<footer>
<ul>
<li> 首页 </li>
<li> 列表 </li>
<li> 我的 </li>
</ul>
</footer>
</StyledFooter>
)
}
}
可透传 props 以及 基于 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'};
`
return (<StyledDiv bg={"lightblue"}>
Apppppp
<StyledInput type="password" ></StyledInput>
</StyledDiv>
)
}
}
款式化任意组件
import React, {Component} from 'react'
import styled from 'styled-components'
export default class App extends Component {render() {const StyledChild = styled(Child)`
background: yellow
`
return (
<div>
<StyledChild></StyledChild>
</div>
)
}
}
function Child(props) {// 子组件记得接管
return (<div className={props.className}>// 子组件记得接管
Child
</div>
)
}
css 的复用、扩大、加强
mport 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:yellow;
`
const StyledButton2 = styled(StyledButton)`
background:red;
`
return (
<div>
App
<StyledButton></StyledButton>
<StyledButton2></StyledButton2>
</div>
)
}
}
增加动画 定义 keyframes
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 (
<div>
<StyledDiv>
</StyledDiv>
</div>
)
}
}
正文完