官网地址 styled-components
最大的特点就是既可以写组件的样式,也可以作为一个react组件来使用,同样写一些小栗子来了解一下。
首先安装:
npm install styled-components 或
cnpm install styled-components 或
yarn add styled-components
引入:
import styled from "styled-components"
创建 在 js 文件中 定义样式标签组件 最后导出:
export const HeaderWrapper = styled.div`
width: 100%;
/* height: 75px; */
background-color: #242221;
.content {
display: flex;
justify-content: space-between;
color: #fff;
}
.red-line {
height: 5px;
background-color: #c20b0b;
}
`
在 jsx || tsx 中使用:
<HeaderWrapper>
<div className="content">
...
</div>
</HeaderWrapper>
嵌套继承样式:
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>
)
}
变量控制样式:
① 第一种方法 通过css进行控制:
//引入css
import styled, {css} from "styled-components"
const Mainstyle = styled.div`
span {
font-size: 14px;
color: yellow;
}
`
const ContextBox = styled(Mainstyle)`
${({num, color}) => css`
width: 200px;
height: 200px;
background: ${color};
p {
font-size: 24px;
color: #fff;
text-align: center;
}
&::after {
display: block;
content: "hello world";
font-size: ${num}px;
}
`}`
export default function(){
return (
<ContextBox num={16} color="green">
<p>styled-components</p>
<span>这是一个span标签</span>
</ContextBox>
)
}
② 通过props进行控制:
import styled from 'styled-components'
export const NotLogin = styled.div`
min-height: 700px;
display: ${props => (!props.isLogin ? 'block' : 'none')};
background-color: #fff;
border: 1px solid #d3d3d3;
border-width: 0 1px;
.inner {
width: 807px;
height: 372px;
margin: 0 auto 0;
background-position: 0 104px;
h2 {
text-indent: -9999px;
}
.btn-login {
cursor: pointer;
display: block;
width: 167px;
height: 45px;
margin: 278px 0 0 482px;
text-indent: -9999px;
}
.btn-login:hover {
background-position: 0 -278px;
}
}
`
使用和上面一样 这里就不做过多的解释了
定义全局样式:
import {createGlobalStyle} from 'styled-components';
引入全局样式,并将标签写在所有标签样式的最上面就可以保证所有样式都可以使用到全局的样式
iconfont图标的全局使用,将iconfont.css修改为iconfont.js
iconfont图标的使用: