[React] Components 와 State

MihyunCho·2021년 5월 6일
0

[Front-end] React / Redux

목록 보기
2/11
post-thumbnail

함수 컴포넌트와 클래스 컴포넌트

// 🔍 함수 컴포넌트 
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
// 🔍 클래스 컴포넌트 (ES6 class) 
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

함수에서 클래스로 변환하기

// 기존 함수형 컴포넌트
function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}
  1. React.Component를 확장하는 동일한 이름의 ES6 class를 생성
  2. render()라고 불리는 빈 메서드를 추가
  3. 함수의 내용을 render() 메서드 안으로 이동
  4. render() 내용 안에 있는 props를 this.props로 변경
  5. 남아있는 빈 함수 선언을 삭제
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

클래스에 로컬 State 추가하기

  1. render() 메서드 안에 있는 this.props.date를 this.state.date로 변경
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
  1. 초기 this.state를 지정하는 class constructor를 추가
class Clock extends React.Component {
  // 클래스 컴포넌트는 항상 props로 기본 constructor를 호출해야 한다.
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

3. 요소에서 date prop을 삭제

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

결과

// 함수형 컴포넌트 -> 클래스 컴포넌트
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
profile
Sic Parvis Magna 🧩

0개의 댓글