React Basics~스타일링 구성 요소/ css_ in _ js

Barbara Streisand
풀어 주다: 2024-10-09 22:47:28
원래의
288명이 탐색했습니다.
  • If we want to write the style as a css style in a javascript file, we can use the styled-components.

  • We need to install the styled components with a command like this npm i styled-components.

・src/Example.js

iimport { useState } from "react";
import styled from "styled-components";

const StyledButton = styled.button`
  margin: auto;
  border-radius: 9999px;
  border: none;
  display: block;
  width: 120px;
  height: 60px;
  font-weight: bold;
  cursor: pointer;
  background: ${({ isSelected }) => (isSelected ? "pink" : "")};

  @media (max-width: 600px) {
    border-radius: 0;
  }
`;

const OrangeButton = styled(StyledButton)`
  background: orange;

  :hover {
    color: red;
    opacity: 0.7;
  }

  span {
    font-size: 2em;
  }
`;

const Example = () => {
  const [isSelected, setIsSelected] = useState(false);

  const clickHandler = () => setIsSelected((prev) => !prev);

  return (
    <>
      <StyledButton isSelected={isSelected} onClick={clickHandler}>
        StyledButton
      </StyledButton>

      <OrangeButton isSelected={isSelected} onClick={clickHandler}>
        <span>OrangeButton</span>
      </OrangeButton>

      <div style={{ textAlign: "center" }}>{isSelected && "Clicked!"}</div>
    </>
  );
};

export default Example;

로그인 후 복사
  1. We need to set the styled components as styeled.element.
    This is an example.
    const StyledButton = styled.button
    //styles
    ;.

  2. We can pass a prop to the styled components like this.
    from:
    to: background: ${({ isSelected }) => (isSelected ? "pink" : "")};

  3. We can set a media query in the styled components like this
    @media (max-width: 600px) {
    border-radius: 0;
    }

  4. We can implement the other style in the styled components like this.
    const OrangeButton = styled(StyledButton)

  5. We can set a pseudo-element in the styled components like this.
    :hover {
    color: red;
    opacity: 0.7;
    }

・The normal button(Gray button) before cliekd.
React Basics~styling component/ css_ in _ js

・The normal button(Pink button) after cliekd.
React Basics~styling component/ css_ in _ js

・The orange button before cliekd.
React Basics~styling component/ css_ in _ js

・The orange button after cliekd.
React Basics~styling component/ css_ in _ js

위 내용은 React Basics~스타일링 구성 요소/ css_ in _ js의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!