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

參考文章

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章