ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 리액트 기본 - Props
    JS&React 2024. 8. 29. 19:28

    Props

    Props는 컴포넌트에 전달하는 인수 같은 것으로 컴포넌트는 전달받은 Props에 따라 표시하는 스타일과 내용을 변경한다.

    동적으로 컴포넌트를 재사용할 수 있도록 Props로 조건을 전달한다.

    아래와 같이 style을 작성하면 번거롭고 코드가 길어진다.

    • src/App.js
    // 다른 파일에서도 사용할 수 있도록 export 한다.
    // export 한것을 import 하면 다른 파일 안에서 사용할 수 있다.
    export const App = () => {
      // 버튼 클릭 시 실행되는 함수 정의
      const onClickButton = () => {
        alert("콘서트 가고 싶다!");
      };
    
      // CSS 객체
      const contentStyle = {
        color: "blue",
        fontSize: "20px",
      };
    
      const contentPinkStyle = {
        color: "pink",
        fontSize: "20px",
      };
    
      return (
        <>
          <h1 style={{ color: "red" }}>두밧두 후쿠오카</h1>
          <p style={contentStyle}>막콘 9/15</p>
          <p style={contentPinkStyle}>휴닝카이 보고싶다</p>
          <button onClick={onClickButton}>버튼</button>
        </>
      );
    };

     

    Props 기본 사용법

    • src/components/ColoredMessage.jsx
    // Props를 객체로 받음
    // Props가 객체로 전달되므로 임의의 이름(props)으로 받는다.
    export const ColoredMessage = (props) => {
      console.log(props);
      const contentStyle = {
        // color: "blue",
        color: props.color,
        fontSize: "20px",
      };
    
      //   return <p style={contentStyle}>막콘 9/15</p>;
      // JSX 안에 자바스크립트를 기술하므로 { }로 감싼다.
      return <p style={contentStyle}>{props.message}</p>;
    };
    • src/App.jsx
    // 다른 파일에서도 사용할 수 있도록 export 한다.
    import { ColoredMessage } from "./components/ColoredMessage";
    
    // export 한것을 import 하면 다른 파일 인에서 사용할 수 있다.
    export const App = () => {
      // 버튼 클릭 시 실행되는 함수 정의
      const onClickButton = () => {
        alert("콘서트 가고 싶다!");
      };
    
      return (
        <>
          <h1 style={{ color: "red" }}>두밧두 후쿠오카</h1>
          {/* Props를 전달한다 */}
          <ColoredMessage color="green" message="온콘살말" />
          {/* <p style={contentPinkStyle}>휴닝카이 보고싶다</p> */}
          <ColoredMessage color="pink" message="휴닝카이 보고싶다" />
          <button onClick={onClickButton}>버튼</button>
        </>
      );
    };

    children

    • src/App.jsx
    // 다른 파일에서도 사용할 수 있도록 export 한다.
    import { ColoredMessage } from "./components/ColoredMessage";
    
    // export 한것을 import 하면 다른 파일 안에서 사용할 수 있다.
    export const App = () => {
      // 버튼 클릭 시 실행되는 함수 정의
      const onClickButton = () => {
        alert("콘서트 가고 싶다!");
      };
    
      return (
        <>
          <h1 style={{ color: "red" }}>두밧두 후쿠오카</h1>
          {/* children 설정 X */}
          {/* <ColoredMessage color="green" message="온콘살말" /> */}
          {/* children(온콘살말) 설정 O */}
          <ColoredMessage color="green">온콘살말</ColoredMessage>
          {/* <p style={contentPinkStyle}>휴닝카이 보고싶다</p> */}
          {/* children 설정 X */}
          {/* <ColoredMessage color="pink" message="휴닝카이 보고싶다" /> */}
          {/* children(휴닝카이 보고싶다) 설정 O */}
          <ColoredMessage color="pink">휴닝카이 보고싶다</ColoredMessage>
          <button onClick={onClickButton}>버튼</button>
        </>
      );
    };
    • src/components/ColoredMessage.jsx
    // Props를 객체로 받음
    // Props가 객체로 전달되므로 임의의 이름(props)으로 받는다.
    export const ColoredMessage = (props) => {
      console.log(props);
      const contentStyle = {
        // color: "blue",
        color: props.color,
        fontSize: "20px",
      };
    
      //   return <p style={contentStyle}>막콘 9/15</p>;
      // JSX 안에 자바스크립트를 기술하므로 { }로 감싼다.
      // return <p style={contentStyle}>{props.message}</p>;
      return <p style={contentStyle}>{props.children}</p>;
    };

     

    Props를 여러번 사용하거나 수가 많을 때 매번 props.~ 라고 표기하는 것은 번거롭다.

    Props 취급 방법은 프로젝트별로 규칙을 정하고 프로젝트 안에서 통일하는 것을 권장한다.

     

    1) 분할 대입과 객체 생략 표기법 사용

    // Props를 객체로 받음
    // Props가 객체로 전달되므로 임의의 이름(props)으로 받는다.
    export const ColoredMessage = (props) => {
      // Props 분할 대입
      const { color, children } = props;
      const contentStyle = {
        // 객체 생략 표기법 사용(속성명과 설정값이 같아서 사용 가능)
        color,
        fontSize: "20px",
      };
    
      //   return <p style={contentStyle}>막콘 9/15</p>;
      // JSX 안에 자바스크립트를 기술하므로 { }로 감싼다.
      // return <p style={contentStyle}>{props.message}</p>;
      return <p style={contentStyle}>{children}</p>; // props. 불필요
    };

     

    2) 인수 단계에서 전개하는 패턴

    // Props를 객체로 받음
    // Props가 객체로 전달되므로 임의의 이름(props)으로 받는다.
    // export const ColoredMessage = (props) => {
    //   // Props 분할 대입
    //   const { color, children } = props;
    //   const contentStyle = {
    //     // 객체 생략 표기법 사용(속성명과 설정값이 같아서 사용 가능)
    //     color,
    //     fontSize: "20px",
    //   };
    
    // 인수의 () 단계애서 분할 대입
    export const ColoredMessage = ({ color, children }) => {
      const contentStyle = {
        color,
        fontSize: "20px",
      };
    
      //   return <p style={contentStyle}>막콘 9/15</p>;
      // JSX 안에 자바스크립트를 기술하므로 { }로 감싼다.
      // return <p style={contentStyle}>{props.message}</p>;
      return <p style={contentStyle}>{children}</p>; // props. 불필요
    };

     

    참고

    모던 자바스크립트로 배우는 리액트 입문

Designed by Tistory.