[React] Components and Props

nothing-99·2022년 9월 3일
0

react

목록 보기
1/4
post-thumbnail

reactjs.org 의 공식문서를 보고 기록을 남긴다.

Components and Props

React Components는 자바스크립트에서의 함수와 유사한 성격을 가지고 있다. props 라는 parameter를 가지고 있고 (React)element 를 return 한다.

(React)element를 만들 때 React.createElement()로 작성해도 되지만 JSX라는 아주 유용한 방법이 있다. JSX는 html과 매우 유사한 형태라 친근하다. JSX로 작성한 코드는 Babel이 React.createElement()로 바꿔주기 때문에 JSX로 작성해도 무방하다!!! ::그냥 JSX로 쓰자::

2가지 형태로 작성

Function Component와 Class Component 2가지 형태로 작성가능하다. 작성 방법만 조금 다를 뿐 같은 역할을 수행한다.

  • Function Component
function Welcom(props) {
  return <h1>Hello, {props.name}</h1>;
}
  • Class Component
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {props.name}</h1>;
  }
}

Component를 이용

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

const root = ReactDOM.createRoot(Document.querySelector('#root');

const element = <Welcome name="RAYC" />;
root.render(element);
  1. root.render(element) 호출
  2. props={name: "RAYC"}와 함께 Welcome component 호출
  3. Welcome component는 <h1>Hello, RAYC</h1> 리턴
  4. DOM 업데이트

코드 Component 단위로 쪼개보기

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
    </div>
  );
}
  • Avatar Component를 만들고 UserInfo Component를 만들어보자
  • 이때, UserInfo Component의 element에 Avatar Component 를 추가하자
function Avatar(props) {
  return (
    <img
      className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}
function UserInfo(props) {
  return (
    <Avatar user={props.user} />
    <div className="UserInfo-name">
      {props.user.name}
    </div>
  );
}
function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />
    </div>
  );
}

const root = ReactDOM.createRoot(
  Document.querySelector('#root');
);

React...
React app은 하나의 App Component를 root.render() 시킨다. Bottum-Up 방식으로 생각하면 좋을 것 같다. 작은 요소의 Component를 만들고 Component들을 모아서 또 다른 상위 Component를 구성하고 최종적으로 App Component로 모두 합쳐지는 방식을 추구하는 것 같다.
-> Component 단위로 생각하자!!

Props를 오직 READ-ONLY

All React components must act like pure functions with respect to their props.

  • [공식문서]

pure function은 parameter로 들어온 변수(값)를 변형시키지 않고 항상 동일한 parameter에 대해서 동일한 값을 리턴하는 함수이다.

즉, Component를 Class 나 Function으로 작성할 때, 절대로 props의 값을 변형시키려고 하면 안된다. React 에서 그렇게 하기로 약속했다!!

그 역할을 하는 존재가 따로 있다. 아직은 비밀~

참조

profile
- RAYC, Vaping Ape, Bitcoin Monkeys holder

0개의 댓글