[Styled Components] Styled Components


Styled Components


JSのCSS(JavaScriptで作成した構成部品を直接挿入するスタイル技術)
タグ付きTemplate Literal構文
スタイルファイルとjsファイルを別々に作成することを推奨します
特長
自動変更
  • CSS→JSスタイルオブジェクト
  • 一意のクラス属性設定
  • 自動設定仕入先Prepix
  • 単純なダイナミックモデリング(propstheme)
  • 設定
    $ npm i styled-components
    $ npm i -D babel-plugin-styled-components
    Babel設定
    module.exports = {
      plugins: ['babel-plugin-styled-components'],
    }

    基本的な使い方

    import styled from 'styled-components'
    
    const App = () => <Button primary/>
    
    // 방법 1
    const Button = styled.button`
      // scss 문법으로 작성
      width: 100%;
    
      // props를 통한 속성 값 적용
      background-color: ${props => props.danger ? 'red' : 'green'};
    
      // props를 통한 속성 적용
      ${props => props.primary && css`
        background: white;
        color: black;
      `}
    `
    
    // 방법 2
    const Button = styled('button')``
    Tagged Template Literaltemplate literalsの発展形態
    ``の内容を文字列値の配列として関数を再実行
    function styled(selector){
      const styledEl = document.querySelector(selector)
      return function(cssText){
        const cssStyles = cssText.toString().trim().split(';')
        const cssKeyValues = cssStyles.map(style => style.split(':'))
        cssKeyValues.forEach(([key, value]) => {
          if(key && value){
            styledEl.style[key]=value
          }
        })
        return styledEl
      }
    }
    
    styled('h1')`
      color: red;
      width: 100px;
    `

    injectGlobal


    グローバルcss設定
    import { injectGlobal } from 'styled-components'
    
    injectGlobal`
      body{
        padding: 0;
        margin: 0;
      }
    `

    extend


    既存の構成部品のプロパティを継承して展開
    const TomatoButton = styled(Button)`
      color: tomato;
    `;
    
    const Anchor = Button.withCompont("a").extend`
      text-decoration: none;
    `;
    他のラベルに簡単に変更して使用することもできます
    <Button as="a" href="/"/>

    keyframes


    アニメーションキーを作成するには
    import styled, { keyframes } from 'styled-components'
    
    const Button = styled.button`
      ${props => props.danger && css`
        animation: ${rotation} 2s liner infinite;
      `}
    `
    
    const ratation = keyframes`
      from{
        transform: rotate(0deg);
      }
      to{
        transform: rotate(360deg);
      }
    `

    attrs


    HTMLタグ要素への属性の追加
    const Input = styled.input.attrs({
      required: true
    })`
      border: 1px solid gray;
    `

    mixin


    再利用可能なcssグループ
    import { css } from 'styled-components'
    
    const awesomCard = css`
      width: 100px;
      height: 100px;  
    `
    
    const Card = styled.div`
      ${awesomCard};
    `

    Nesting


    重複するサブ構成部品を選択可能
    const App = () => (
      <Wrapper>
        <Item>1</Item>
      </Wrapper>
    )
    
    const Wrapper = styled.div`
      ${Item} {
        color: red;
      }
    `
    
    const Item =  styled.div`
      width: 100px;
    `

    組み込み関数の使用

    polishedライブラリの使用
    import { darken, lighten } from 'polished';
    
    const Btn = styled.button`
      &:hover {
        color: ${lighten(0.1, 'red')}
      }
      &:active {
        color: ${darken(0.1, 'gray')}
      }
    
    `

    Theming


    theme.js
    const theme = {
      mainColor: "green",
      dangerColor: "red"
    }
    export default themes
    app.js
    import styled, { ThemeProvider } from 'styled-components'
    import theme from './theme'
    
    const App = () => (
      <ThemeProvider theme={theme}>
        <Button>hi</Button>
      </ThemeProvider>
    )
    
    const Button = styled.button`
      color: ${props => props.theme.mainColor};
    `

    global-style


    resetComponentではなくHTML Elementsを管理
    npm i styled-reset
    createGlobalStyle
    import { createGlobalStyle, css } from "styled-components";
    import reset from "styled-reset";
    import customReset from "./customReset.scss";
    
    const GlobalStyle = createGlobalStyle`
        ${reset};
        ${customReset}; // 사용자 정의 스타일
    
        html {
          font-size: 62.5%; //1rem = 10px;
        }
    
        ${({ theme }) => {
          return css`
            body {
              font-family: ${theme.fonts.family.base};
              font-weight: ${theme.fonts.weight.normal};
              font-size: ${theme.fonts.size.base};
            }
          `;
        }}
    `;
    
    export default GlobalStyle;
    適用
    定義されたグローバルスタイル要素は、プロジェクトとしてトピックを受信するためにThemeProviderのサブ要素として配置されます.
    const App = () => (
      <ThemeProvider theme={theme}>
        <GlobalStyle />
        <Header switchTheme={switchTheme} />
        <Container currentThemeText={currentThemeText} />
      </ThemeProvider>
    )
    返信スタイルを使用したコンポーネント