[React] component와 props의 이해

17646 단어 ReactReact

1. component


💡 컴포넌트란 ?

어떠한 JSX를 반환하는 함수
아래 코드의 SaveBtn() ConfirmBtn() App() 는 함수형 컴포넌트

// 함수형 컴포넌트
function SaveBtn() {
  return <button>Save Changes</button>;
}
function ConfirmBtn() {
  return <button>Confirm</button>;
}
function App() {
  return (
	// JSX 내부
    <div>
      <SaveBtn />
      <ConfirmBtn />
    </div>
  );
}



2. props


⭐ props의 필요성

같은 style을 같지만 기능이 다른 두 개의 버튼이 있다.
style을 중복하여 코드를 작성하지 않고, 변경되는 부분(text)만 변경되도록 할 수는 없을까?

function SaveBtn() {
  return (
    <button
      // 중복되는 style
      style={{
        backgroundColor: "tomato",
        color: "white",
        paddig: "10px 20px",
        border: 0,
        borderRadius: 10,
      }}
    >
      // 변경되는 부분
      Save Changes
    </button>
  );
}
function ConfirmBtn() {
  return (
    <button
      // 중복되는 style
      style={{
        backgroundColor: "tomato",
        color: "white",
        paddig: "10px 20px",
        border: 0,
        borderRadius: 10,
      }}
    >
      // 변경되는 부분
      Confirm
    </button>
  );
}



props란?

해당 함수가 전달받는 첫번째이자 유일한 인자

  • 컴포넌트들은 ( )argument(인자)를 받음
  • 여기서 이 argument(인자)를 props(properties)라고 부름
  • props는 아래 예제의 text와 같이 다양한 properties를 갖고 있는 객체
function Btn(props) {
  return (
    <button
      style={{
        backgroundColor: "tomato",
        color: "white",
        paddig: "10px 20px",
        border: 0,
        borderRadius: 10,
      }}
    >
      {props.text}
    </button>
  );
}
function App() {
  return (
    <div>
      // Btn의 properties인 text
      <Btn text="Save Changes" />
      <Btn text="Continue" />
    </div>
  );
}

✅ Btn( )함수를 불러 text라는 인자를 Btn({text:"save changes"}) 와 같이 객체의 형태로 보냄
✅ 위 props는 객체의 형태로 Btn( )함수의 첫번째 인자로 들어감

💯 컴포넌트의 재사용을 가능하게 해준다!!



🎁 또다른 사용법

// 지름길! property를 object로부터 꺼내는 방법
function Btn({ text }) {
  return (
    <button
      style={{
        backgroundColor: "tomato",
        color: "white",
        paddig: "10px 20px",
        border: 0,
        borderRadius: 10,
      }}
    >
      {text}
    </button>
  );
}



🎨 style 안에서의 if else

변경되는 text뿐만 아니라 style에서도 차이를 줄 수 있다.

  • 위 사진과 같이 같은 형태를 가졌지만, text뿐만 아니라 font 크기에서도 차이가 있는 것을 볼 수 있다.
function Btn({ text, big }) {
  return (
    <button
      style={{
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
        fontSize: big ? 20 : 16,
      }}
    >
      {text}
    </button>
  );
}
function App() {
  return (
    <div>
      <Btn text="Save Changes" big={true} />
      <Btn text="Continue" big={false} />
    </div>
  );
}



📜 참고


ReactJS로 영화 웹 서비스 만들기

좋은 웹페이지 즐겨찾기