スタイル→コンポーネント→(4)アニメーションとセレクタ



基本的な使い方


  • キーを最初に読み込みます.import { keyframes } from "styled-components";

  • キーフレームを使用してアニメーションを定義します.

  • 適用するスターコンポーネントにアニメーションアトリビュートを適用します.animation: ${animation} 1.5s linear infinite;
  • import styled, { keyframes } from "styled-components";
    
    const Wrapper = styled.div`
      display: flex;
    `;
    
    //styled-componets와 상관없고 그냥 CSS문법이다.
    const animation = keyframes`
      0% {
        transform: rotate(0deg);
        border-radius: 0px;
      }
      50% {
        transform: rotate(360deg);
        border-radius: 100px;
      }
      100% {
        transform: rotate(0deg);
        border-radius: 0px;
      }
    `;
    
    
    const Box = styled.div`
      height: 200px;
      width: 200px;
      background-color: tomato;
      animation: ${animation} 1.5s linear infinite;
    `;
    
    function App() {
      return (
        <Wrapper>
          <Box />
        </Wrapper>
      );
    }
    
    export default App;
    

    恒星素子のセレクタ

    모든 태그를 스타일 컴포넌트화 하지 않아도 간단한 문법으로 스타일컴포넌트 내의 Selector를 지정하여 속성을 부여해줄 수 있다.
  • const Box = styled.div`
      height: 200px;
      width: 200px;
      background-color: tomato;
      animation: ${animation} 1.5s linear infinite;
      display: flex;
      justify-content: center;
      align-items: center;
    
      //Box span{}과 같다.
      span {
        font-size: 50px;
        //span:hover{}와 같다.
        &:hover {
          font-size: 80px
        }
        //span:active{}와 같다.
        &:active {
          opacity: 0;
        }
      }
    `;
    
    function App() {
      return (
        <Wrapper>
          <Box>
            <span>😃</span>
          </Box>
        </Wrapper>
      );
    }
    

    スタイル要素の直接配置

    위 예제의 span을 ${Emoji}로 변경해준다면 태그에 제한되지 않고 Emoji컴포넌트가 p,h1 등등 다른 태그로 변경되어도 속성들을 계속 적용되게 할 수 있다.
    const Emoji = styled.span`
      font-size: 50px;
        &:active {
          opacity: 0;
        }
    `;
    
    const Box = styled.div`
      height: 200px;
      width: 200px;
      background-color: tomato;
      animation: ${animation} 1.5s linear infinite;
      display: flex;
      justify-content: center;
      align-items: center;
    
      ${Emoji} { 
        &:hover {
          font-size: 98px
        }
      }
    `;
    
    function App() {
      return (
        <Wrapper>
          <Box>
            <Emoji as="p">😃</Emoji>
          </Box>
        </Wrapper>
      );
    }