css in js开发利器 - styled-components(样式组件)

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"]

参考文章

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值