安装
npm install styled-components 或
cnpm install styled-components 或
yarn add styled-components
引入
import styled from "styled-components"
基本用法:
const ContextBox = styled.div`
width: 200px;
height: 200px;
background: red;
`
export default function(){
return (
<ContextBox></ContextBox>
)
}
给子元素设置样式
const ContextBox = styled.div`
width: 200px;
height: 200px;
background: red;
p {
font-size: 24px;
color: #fff;
text-align: center;
}
&::after {
display: block;
content: "hello world";
font-size: 30px;
}
`
export default function(){
return (
<ContextBox>
<p>styled-components</p>
</ContextBox>
)
}
嵌套继承样式:
const Mainstyle = styled.div`
span {
font-size: 14px;
color: yellow;
}
`
const ContextBox = styled(Mainstyle)`
width: 200px;
height: 200px;
background: red;
p {
font-size: 24px;
color: #fff;
text-align: center;
}
&::after {
display: block;
content: "hello world";
font-size: 30px;
}
`
export default function(){
return (
<ContextBox>
<p>styled-components</p>
<span>这是一个span标签</span>
</ContextBox>
)
}
变量控制样式:
const Mainstyle = styled.div`
span {
font-size: 14px;
color: yellow;
}
`
const ContextBox = styled(Mainstyle)`
width: 200px;
height: 200px;
background: red;
p {
font-size: 24px;
color: #fff;
text-align: center;
}
&::after {
display: block;
content: "hello world";
font-size: 30px;
}
`
export default function(){
return (
<ContextBox>
<p>styled-components</p>
<span>这是一个span标签</span>
</ContextBox>
)
}