styled-components 是一个常见的 css in js 类库,和所有同类型的类库一样,通过 js 赋能解决了原生 css 所不具备的能力,比如变量、循环、函数等。
注意:有时候 React 版本和 styled-components 版本不匹配时使用 styled-components 会有 hook 报错,要升级一下 React 版本。
一、安装
npm install --save styled-components
二、使用文档
1. 基本使用
import styled, { css } from 'styled-components';
/* 创建了一个Wrapper样式组件,该组件渲染之后是一个div标签 */
const Wrapper = styled.div`
/* 应用于Wrapper组件本身和Wrapper组件里的所有标签 */
color: blue;
/* 应用于Wrapper组件里的className为red的标签 */
.red {
color: red;
}
/* 应用于className为green的Wrapper组件 */
&.green{
color: green;
}
${props => props.primary && css`
background: palevioletred;
`}
`;
/* Wrapper组件跟其他的react组件一样,只不过现在他们有了自己的样式 */
<Wrapper primary>
Hello World!
<p className="red">我是红色文字。</p>
</Wrapper>
<Wrapper className="green">Wrapper组件</Wrapper>
另外一种生成样式组件的写法:
const Wrapper = styled.div({
color: 'red'
});
2. 扩展已有样式
const BorderWrapper = styled(Wrapper)`
border: 5px solid #000;
`;
3. 修改标签类型
// 把div标签换成a标签
const LinkWrapper = Wrapper.withComponent('a');
4. 添加动画keyframes
import styled, { keyframes } from 'styled-components';
const MyAnimation = keyframes`
from {
padding-left: 0;
background: #991302;
}
to {
padding-left: 50px;
background: #009317;
}
`;
const Wrapper = styled.div`
animation: ${MyAnimation} 2s linear infinite alternate;
`;
三、完善你的styled-components开发环境
1. VSCode插件
VSCode 对 styled-components 高亮插件:vscode-styled-components
2. stylelint
stylelint 对 styled-components 的语法会报错,要下载一个包做一下兼容:
- 安装 stylelint-config-styled-components 包
-
然后,在 .stylelintrc
文件中添加配置:"processors": ["stylelint-processor-styled-components"]
。
参考文章
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)