react学习总结系列-styled-components

这一篇主要整理关于React的CSS插件styled-components。这个插件是我一开始学习React跟做项目的时候推荐并使用的。用了之后觉得这个插件确实很适合React的项目,有无缝对接的效果。

这里也是留一下styled-components官网文档地址:

https://www.styled-components.com/docs

安装

简单说一下安装。

代码1 NPM&CDN安装

1
2
3
4
5
/* NPM install */
npm install --save styled-components

/* CDM install */
; <script src=" https://unpkg.com/styled-components/dist/styled-components.min.js" />

简单使用

styled-components使用也比较简单。最简单的写法就是声明styled变量,然后把css样式以模板字符串形式写入,最后把这个变量以React组件的形式写到render()中就可以了。

代码2 styled-components简单例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;

const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;

render(
<Wrapper>
<Title>
Hello World, this is my first styled component!
</Title>
</Wrapper>
);

上面是官网用例。可以看到,其实是把css样式表嵌入到JavaScript中,然后通过styled-components转成组件,然后再在其他组件中使用。所以使用起来非常简单。

传递参数

因为style-components把css样式表转成一个个的组件,所以也可以实现一些样式的传参。

代码2 传递参数,对代码1的修改

1
2
3
4
5
6
7
8
9
10
11
12
13
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: \function(e){return e.inputColor||"palevioletred"};
`;

render(
<div>
<Title inputColor="rebeccapurple" >
Hello World, this is my first styled component!
</Title>
</div>
);

代码2中,在变量Input的样式表中,color后面是跟着一个\,接着一个匿名函数。这个匿名函数有一个传参e,函数中会返回e.inputColor或默认值"palevioletred"。在render()函数中,第二个Input组件标签中声明了一个inputColor的属性值,而第一个没有。在最终的显示上,第一个组件字体样式是紫罗兰红(palevioletred),第二个组件字体样式是丽贝卡紫(rebeccapurple)。也就是说,变量Input的样式表中的匿名函数,传入的参数e应该指向当前组件对象

传递参数的类型还可以是真假值。组件的属性上,可以直接声明一个属性并不传值,匿名函数中可将直接判断是否存在这个属性,以确定返回的样式值。

代码3 传递属性,对代码1的修改

1
2
3
4
5
6
7
8
9
10
11
12
13
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: ${props => props.primary ? "palevioletred" : "white"};
`;

render(
<div>
<Title primary >
Hello World, this is my first styled component!
</Title>
</div>
);

组件继承

一个项目中或多或少会出现一些组件上设计样式的类似,比如不同级标题可能HTML样式,尺寸是一样的,但是颜色会不同。如果都是写成独立的组件样式表,则会出现代码冗余,不好维护。这种情况下就可以考虑使用组件继承。

代码4 组件继承,对代码1的修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;

const SecondTitle = styled(Title)`
font-size: 1em;
font-weight: bold;
`

render(
<div>
<Title>
Hello World, this is my first styled component!
</Title>
<SecondTitle>
This is the second title!
</SecondTitle>
</div>
);

如果Title中没有样式的话,那它就是直接继承react.component的组件,仍然可以被继承。

动画

styled-components对动画也有很好的支持。内置了keyframes来实现CSS3中的@keyframes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const rotate360 = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;

const Rotate = styled.div`
display: inline-block;
animation: ${rotate360} 2s linear infinite;
padding: 2rem 1rem;
font-size: 1.2rem;
`;

render(
<Rotate>&lt; 💅 &gt;</Rotate>
);

除了上面介绍的方面之外,styled-component插件还有一些更复杂的用法,但是目前大部分的样式实现只要上面这些内容掌握了,在项目中也能解决大部分的问题了。剩下的以后有涉及到会再介绍。

下一篇将会介绍redux及react-redux插件。