[React] Component와 Props

vanLan·2022년 11월 15일
0

React

목록 보기
3/11
post-thumbnail

🔑 리액트 컴포넌트(Component)란?

  • 리액트로 만들어진 앱을 이루는 최소한의 단위.
  • 뷰를 독립적으로 구성하여 재사용 할 수 있고 이를 통해 새로운 컴포넌트를 쉽게 만들수 있다.
  • props를 입력받아 state 상태에 따라 DOM Node를 출력하는 함수.
  • 컴포넌트 이름은 항상 대문자로 시작하도록 한다.

🗝 함수형 컴포넌트(Sateless Functional Component)

  • 가장 간단하게 컴포넌트를 정의하는 방법은 자바스크립트 함수를 작성하는 것.

    
    function Welcom(props) {
      return <h1>Hello, {props.name}</h1>;
    }

🗝 클래스형 컴포넌트(Class Component)

  • 컴포넌트 구성 요소, 리액트 생명주기를 모두 포함하고 있다.

  • 프로퍼티, state, 생명주기 함수가 필요한 구조의 컴포넌트를 만들 때 사용.

    
    class Welcome extends React.Component {
      // 생성자
      constructor(props) {
        super(props);
      }
      
      // 클래스형 컴포넌트는 render() 필수
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }

💡 컴포넌트 렌더링

  • DOM 태그 뿐 아니라, '사용자 정의 컴포넌트'를 이용하여 React 엘리먼트를 나타낼 수도 있다.
    const element = <Welcome name='Vanlan' />;
  • 사용자 정의 컴포넌트로 작성한 엘리먼트의 atrribute와 children을 해당 컴포넌트에 단일 객체로 전달하는데, 이를 'props' 라고 한다.

💡 컴포넌트 합성

  • 컴포넌트는 자신의 출력에 다른 컴포넌트를 참조할 수 있다.

    const Header = (props) => {
      return (
        <div>{props.title}</div>
      );
    };
    
    function App() {
      return (
        <div className='App'>
          // Header 컴포넌트에 props로 title속성을 전달해 재사용.
          <Header title={'Learn React A'} />
          <Header title={'Learn React B'} />
          <Header title={'Learn React C'} />
        </div>
      );
    }
  • props는 읽기 전용이다.
    (모든 React 컴포넌트는 props를 다룰 때 반드시 순수 함수처럼 동작해야 한다.)

  • props.children: 컴포넌트의 열린태그와 닫힌태그 사이에 입력되는 자식값.

    // 1. 사용자 정의 컴포넌트가 일반적인 html 태그의 구조와 비슷할 때.
    export default function Button(props) {
      return <button onClick={props.handleClick}>{props.children}</button>
    }
    <Button onClick={() => alert('submit')}>제출하기</Button>
    <Button onClick={() => alert('delete')}>삭제하기</Button>
    <Button onClick={() => alert('add')}>추가하기</Button>
    
    // 2. 컴포넌트에 다른 컴포넌트를 전달해야 할 때.
    <Layout><Apage /></Layout>
    <Layout><Bpage /></Layout>
    <Layout><Cpage /></Layout>

profile
프론트엔드 개발자를 꿈꾸는 이

0개의 댓글