컴포넌트와 Props

김상현·2020년 6월 18일
0

React

목록 보기
3/16

컴포넌트

  • 컴포넌트는 UI가 어떻게 보여야하는지 정의하는 React element를 output으로 하는 함수. 함수형과 클래스로 정의할 수 있음.
const cp = (props) => <h1>Hello, {props.name}</h1>; 
// 함수형

class cp extends React.Componet {
  render() {
    return <h1>Hello, {props.name}</h1>;
  }
}
// 클래스

  • React가 사용자 정의 컴포넌트로 작성한 element를 발견하면 JSX attribute와 자식을 해당 컴포넌트에 단일 객체로 전달함. 이 객체를 Props라고 함
const Example = (props) => <h1>Hello, {props.name}</h1>;
//Component의 이름은 항상 대문자로 시작

const element = <Example name="sara" />;
ReactDOM.render(
  <React.StrictMode>{element}</React.StrictMode>,
  document.getElementById("root")
);

Props

  • Props는 읽기 전용으로 컴포넌트의 자체 props를 수정하면 안됨. 모든 React 컴포넌트는 자신의 props를 다룰 때 반드시 순수함수처럼 동작해야함.
const Example = (props) => <h1>Hello, {props.name}</h1>;
// 입력 값을 바꾸려하지 않고 항상 동일한 입력값에 대해 동일한 결과 반환

const Example2 = (props) => {
  props.name = "Kim"
  //입력 값을 바꿈
  return <h1>Hello, {props.name}</h1>;
}

0개의 댓글