React : Element 에 스타일 입히기

코일·2022년 1월 19일
0

learn-react

목록 보기
4/4
post-thumbnail

엘리멘트에 스타일을 입혀보자

<body>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <div id="root"></div>
    <style>
      .button {
        background-color: #4caf50; /* Green */
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
      }

      .button2 {
        background-color: #008cba;
      } /* Blue */
      .button3 {
        background-color: #f44336;
      } /* Red */
      .button4 {
        background-color: #e7e7e7;
        color: black;
      } /* Gray */
      .button5 {
        background-color: #555555;
      } /* Black */
    </style>

    <script type="text/babel">
      const rootElement = document.getElementById("root");

      const element = (
        <>
          <button className="button">Green</button>
          <button className="button button2">Blue</button>
          <button className="button button3">Red</button>
          <button className="button button4">Gray</button>
					<button className="button button5">Black</button>
					// 다른 엘레멘트 들과 혼동 될수 있기 때문에
					**// button에도 class가 아닌 className 을 준다.(형평성)**
        </>
      );

      ReactDOM.render(element, rootElement);
    </script>
  </body>

공통되는 버튼은 .button으로 묶고 색상변화만 새로운 클래스를 주었다.

  • 의미있는 클래스명으로 변경해주었다.

  • 스타일 속성을 추가하였다. (인라인)

<body>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <div id="root"></div>
    <style>
      .button {
        background-color: #4caf50; /* Green */
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
      }

      **.blue** {
        background-color: #008cba;
      } 
      .**red** {
        background-color: #f44336;
      } 
      .**gray** {
        background-color: #e7e7e7;
        color: black;
      } 
      .**black** {
        background-color: #555555;
      } 
    </style>

    <script type="text/babel">
      const rootElement = document.getElementById("root");

      const element = (
        <>
          <button className="button" style={{ borderRadius: "50%" }}>
            Green
          </button>
          <button className="button **blue**" style={{ borderRadius: "8px" }}>
            Blue
          </button>
          <button className="button **red**">Red</button>
          <button className="button **gray**">Gray</button>
          <button className="button **black**">Black</button>
        </>
      );

      ReactDOM.render(element, rootElement);
    </script>
  </body>

리액트의 장점 활용하기

리액트의 장점은 JS와 HTML를 서로 섞어쓰는 JSX를 사용하고, 그 안에서 함수 등 이것저것 만들 수 있었다.

함수로 만들어보자

function Button({ props }) {
        return <button {...props} />;
      }

엥?

당연하다 . props를 { } 안에 넣었기 때문이다. ( { } 안에는 속성을 개별적으로 넣음 )

props란 속성들의 정보를 모두 가진다.

			 <>
          <button className="button" **style={{ borderRadius: "50%" }}**>
            Green
          </button>
          <button className="button blue" **style={{ borderRadius: "8px" }}**>
            Blue
          </button>
          <button className="button red">Red</button>
          <button className="button gray">Gray</button>
          <button className="button black">Black</button>
        </>

다시한번 적어보자면, 아래와 같다고 볼 수 있다.

function Button( {className, style, ...rest} ) {
        return <button {...props} />;
      }

응용해보기.

	<script type="text/babel">
      const rootElement = document.getElementById("root");

		// *** Point 1 ***
      function Button({ className, color, style, ...rest }) { 
        return (
          <button
            className={`button ${className} ${color}`} 
            style={{ fontSize: 50, ...style }}
            {...rest}
          />
        );
      }

      const element = (
        <>
          <Button className="button" style={{ borderRadius: "50%" }}>
            Green
          </Button>
					// *** Point 2 ***
          <Button
            className="color blue"
            style={{ **fontSize: 15**, borderRadius: "8px" }} 
          >
            Blue
          </Button>
          <Button className="color red">Red</Button>
          <Button className="color gray">Gray</Button>
          <Button className="color black">Black</Button>
        </>
      );

      ReactDOM.render(element, rootElement);
    </script>
	// *** 1 ***
      function Button({ className, **color**, style, ...rest }) { 
        return (
          <button
            className={`button ${className} ${**color**}`} 
            style={{ fontSize: 50, ...style }}
            {...rest}
          />
        );
      }

* Point 1 *

엘리멘트의 속성에는 있는데 파라미터에 들어가지 않았다면, ...rest 에서 처리해준다

className='button blue' 와 같다.

앨리멘트의 className을 color로 변경하려면 어떻게 해야할까?

const element = (
        <>
          <Button color="button" style={{ borderRadius: "50%" }}>
            Green
          </Button>
          <Button color="blue" style={{ **fontSize: 15,** borderRadius: "8px" }}>
            Blue
          </Button>
          <Button color="red">Red</Button>
          <Button color="gray">Gray</Button>
          <Button color="black">Black</Button>
        </>
      );

props를 className에서 color로 바꾸면서 엘리멘트에서의 className은 더 이상 의미없다.

function Button({ **color**, style, ...rest }) {
        return (
          <button
            className={`button ${**color**}`}
            style={{ fontSize: 50, ...style }}
            {...rest}
          />
        );
      }

파라미터로 속성 그 자체를 받아버린다.

* Point 2 *

// *** 2 ***
          <Button
            className="color blue"
            style={{ **fontSize: 15**, borderRadius: "8px" }} >
            Blue
          </Button>

위에 엘리멘트와 함수를 이용해서 공통적인 부분은 스타일로 빼돌렸고,

custom이 필요한 부분은 인라인 style로 넣어줄 수 있다.

리액트 스타일 우선순위

인라인태그 속성 > 파라미터 속성 > className

또는

style > className


정리

리액트 Element에 스타일 입히기

className → 문자열 ( CSS 에 넘겨줄 때 처럼 사용하는거 )

style → 객체, 카멜케이스, className 보다 먼저 (인라인스타일)

우선순위style > className


profile
How do you get what you want?🤔🤔

0개의 댓글