React 클래스 구성 요소


React 16.8 이전에는 Class 구성 요소가 React 구성 요소의 상태와 수명 주기를 추적하는 유일한 방법이었습니다. 기능 구성 요소는 "상태 비저장"으로 간주되었습니다.

Hooks가 추가되어 Function 구성 요소는 이제 Class 구성 요소와 거의 동일합니다. 차이점은 너무 미미하여 React에서 Class 구성 요소를 사용할 필요가 없을 것입니다.

Function 구성 요소가 선호되지만 현재 React에서 Class 구성 요소를 제거할 계획은 없습니다.

이 섹션에서는 React에서 Class 구성 요소를 사용하는 방법에 대한 개요를 제공합니다.

이 섹션을 건너뛰고 대신 함수 구성 요소를 사용하십시오.


반응 구성 요소

구성 요소는 독립적이고 재사용 가능한 코드 비트입니다. 그들은 JavaScript 함수와 같은 목적을 제공하지만 고립되어 작동하고 render() 함수를 통해 HTML을 반환합니다.

구성 요소는 클래스 구성 요소와 함수 구성 요소의 두 가지 유형으로 제공되며 이 장에서는 클래스 구성 요소에 대해 배웁니다.


클래스 구성 요소 만들기

React 컴포넌트를 생성할 때 컴포넌트의 이름은 대문자로 시작해야 합니다.

구성 요소는 extends React.Component명령문을 포함해야 하며 이 명령문은 React.Component에 대한 상속을 생성하고 구성 요소에 React.Component의 기능에 대한 액세스 권한을 부여합니다.

구성 요소에도 메서드가 필요하며 render()이 메서드는 HTML을 반환합니다.

예시

라는 클래스 구성 요소를 만듭니다. Car

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

이제 React 애플리케이션에는 요소를 반환하는 Car라는 구성 <h2>요소가 있습니다.

애플리케이션에서 이 구성요소를 사용하려면 일반 HTML과 유사한 구문을 사용하십시오. <Car />

예시

Car"루트" 요소에 구성요소를 표시합니다 .

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


w3schools CERTIFIED . 2022

인증을 받으세요!

React 모듈을 완료하고, 연습을 하고, 시험을 보고, w3schools 인증을 받으세요!!

$95 등록

구성 요소 생성자

구성 요소에 함수가 있는 경우 constructor()구성 요소가 시작될 때 이 함수가 호출됩니다.

생성자 함수는 구성 요소의 속성을 시작하는 곳입니다.

React에서 컴포넌트 속성은 이라는 객체에 보관해야 합니다 state.

state이 튜토리얼의 뒷부분에서 더 자세히 배우게 될 것 입니다.

생성자 함수는 부모 구성 요소의 생성자 함수를 실행하는 문을 포함하여 부모 구성 요소의 상속을 존중하는 곳이기도 하며 구성 요소 super() 는 상위 구성 요소의 모든 기능에 액세스할 수 있습니다( React.Component).

예시

Car 구성 요소에서 생성자 함수를 만들고 color 속성을 추가합니다.

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a Car!</h2>;
  }
}

render() 함수에서 color 속성을 사용하십시오:

예시

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a {this.state.color} Car!</h2>;
  }
}


소품

구성 요소 속성을 처리하는 또 다른 방법은 를 사용하는 것 props입니다.

소품은 함수 인수와 같으며 속성으로 구성 요소에 보냅니다.

props다음 장에서 더 자세히 배울 것 입니다.

예시

속성을 사용하여 색상을 Car 구성 요소에 전달하고 render() 함수에서 사용합니다.

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.color} Car!</h2>;
  }
}

ReactDOM.render(<Car color="red"/>, document.getElementById('root'));


생성자의 소품

구성 요소에 생성자 함수가 있는 경우 props는 항상 생성자에 전달되고 메서드를 통해 React.Component에도 전달되어야 합니다 super().

예시

class Car extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>I am a {this.props.model}!</h2>;
  }
}

ReactDOM.render(<Car model="Mustang"/>, document.getElementById('root'));


구성 요소의 구성 요소

다른 구성 요소 내부의 구성 요소를 참조할 수 있습니다.

예시

Garage 구성 요소 내에서 Car 구성 요소를 사용합니다.

class Car extends React.Component {
  render() {
    return <h2>I am a Car!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    return (
      <div>
      <h1>Who lives in my Garage?</h1>
      <Car />
      </div>
    );
  }
}

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


파일의 구성요소

React는 코드를 재사용하는 것이므로 일부 구성 요소를 별도의 파일에 삽입하는 것이 현명할 수 있습니다.

그렇게 하려면 파일 확장자를 가진 새 파일을 만들고 그 .js 안에 코드를 넣으십시오.

파일은 React를 가져오는 것으로 시작해야 하고(이전과 마찬가지로) 문으로 끝나야 합니다 export default Car;.

예시

이것은 새 파일입니다. 이름은 다음 Car.js과 같습니다.

import React from 'react';

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

export default Car;

구성 요소 를 사용하려면 Car응용 프로그램에서 파일을 가져와야 합니다.

예시

이제 Car.js응용 프로그램에서 파일을 가져오고 Car 여기에서 만든 것처럼 구성 요소를 사용할 수 있습니다.

import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';

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


React 클래스 구성 요소 상태

React Class 구성 요소에는 내장 state객체가 있습니다.

state컴포넌트 생성자 섹션에서 앞서 사용한 것을 눈치 채셨을 것입니다.

state개체는 구성 요소에 속한 속성 값을 저장하는 위치입니다 .

개체가 변경 되면 state구성 요소가 다시 렌더링됩니다.


상태 개체 만들기

상태 개체는 생성자에서 초기화됩니다.

예시

state생성자 메서드에서 개체를 지정합니다 .

class Car extends React.Component {
  constructor(props) {
    super(props);
  this.state = {brand: "Ford"};
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

상태 개체는 원하는 만큼 속성을 포함할 수 있습니다.

예시

구성 요소에 필요한 모든 속성을 지정합니다.

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

state개체 사용

다음 구문 state을 사용하여 구성 요소의 아무 곳에서나 개체 를 참조하십시오 .this.state.propertyname

예시:

메서드 state에서 개체를 참조하십시오 .render()

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
      </div>
    );
  }
}


state개체 변경

상태 개체의 값을 변경하려면 this.setState()메서드를 사용합니다.

개체 의 값이 state변경되면 구성 요소가 다시 렌더링됩니다. 즉, 출력이 새 값에 따라 변경됩니다.

예시:

onClick색상 속성을 변경하는 이벤트가 있는 버튼을 추가합니다 .

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

항상 setState()메서드를 사용하여 상태 개체를 변경합니다. 구성 요소가 업데이트되었음을 ​​확인하고 render() 메서드(및 기타 모든 수명 주기 메서드)를 호출하도록 합니다.


구성 요소의 수명 주기

React의 각 구성 요소에는 세 가지 주요 단계에서 모니터링하고 조작할 수 있는 수명 주기가 있습니다.

세 단계는 마운팅 , 업데이트마운트 해제 입니다.


설치

마운팅은 요소를 DOM에 넣는 것을 의미합니다.

React에는 구성 요소를 마운트할 때 이 순서대로 호출되는 4가지 기본 제공 메서드가 있습니다.

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

render()메서드는 필수이며 항상 호출되며 다른 메서드는 선택 사항이며 정의하면 호출됩니다.


constructor

constructor()메서드는 구성 요소가 시작될 때 다른 것보다 먼저 호출되며 초기 state및 기타 초기 값을 설정하는 자연스러운 위치입니다.

constructor()메서드는 props인수로 ,를 사용하여 호출되며 항상 super(props)다른 것보다 먼저 호출하여 시작해야 합니다. 이렇게 하면 부모의 생성자 메서드가 시작되고 구성 요소가 부모( React.Component)에서 메서드를 상속할 수 있습니다.

예시:

constructor메소드는 컴포넌트를 만들 때마다 React에 의해 호출됩니다.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

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


getDerivedStateFromProps

메서드 는 getDerivedStateFromProps()DOM에서 요소를 렌더링하기 직전에 호출됩니다.

이것은 state이니셜을 기반으로 개체 를 설정하는 자연스러운 위치 props입니다.

It takes state as an argument, and returns an object with changes to the state.

The example below starts with the favorite color being "red", but the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:

Example:

The getDerivedStateFromProps method is called right before the render method:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


render

The render() method is required, and is the method that actually outputs the HTML to the DOM.

Example:

A simple component with a simple render() method:

class Header extends React.Component {
  render() {
    return (
      <h1>This is the content of the Header component</h1>
    );
  }
}

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


componentDidMount

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the DOM.

Example:

At first my favorite color is red, but give me a second, and it is yellow instead:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

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


Updating

The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component's state or props.

React has five built-in methods that gets called, in this order, when a component is updated:

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

The render() method is required and will always be called, the others are optional and will be called if you define them.


getDerivedStateFromProps

Also at updates the getDerivedStateFromProps method is called. This is the first method that is called when a component gets updated.

This is still the natural place to set the state object based on the initial props.

The example below has a button that changes the favorite color to blue, but since the getDerivedStateFromProps() method is called, which updates the state with the color from the favcol attribute, the favorite color is still rendered as yellow:

Example:

If the component gets updated, the getDerivedStateFromProps() method is called:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


shouldComponentUpdate

In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not.

The default value is true.

The example below shows what happens when the shouldComponentUpdate() method returns false:

Example:

Stop the component from rendering at any update:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

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

Example:

Same example as above, but this time the shouldComponentUpdate() method returns true instead:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return true;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

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


render

The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.

The example below has a button that changes the favorite color to blue:

Example:

Click the button to make a change in the component's state:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

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


getSnapshotBeforeUpdate

In the getSnapshotBeforeUpdate() method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.

If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and after one second, the favorite color becomes "yellow".

This action triggers the update phase, and since this component has a getSnapshotBeforeUpdate() method, this method is executed, and writes a message to the empty DIV1 element.

Then the componentDidUpdate() method is executed and writes a message in the empty DIV2 element:

 

Example:

Use the getSnapshotBeforeUpdate() method to find out what the state object looked like before the update:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    );
  }
}

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


componentDidUpdate

The componentDidUpdate method is called after the component is updated in the DOM.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and the color becomes "yellow".

This action triggers the update phase, and since this component has a componentDidUpdate method, this method is executed and writes a message in the empty DIV element:

Example:

The componentDidUpdate method is called after the update has been rendered in the DOM:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById("mydiv").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <div id="mydiv"></div>
      </div>
    );
  }
}

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


Unmounting

The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.

React has only one built-in method that gets called when a component is unmounted:

  • componentWillUnmount()

componentWillUnmount

The componentWillUnmount method is called when the component is about to be removed from the DOM.

Example:

Click the button to delete the header:

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
      myheader = <Child />;
    };
    return (
      <div>
      {myheader}
      <button type="button" onClick={this.delHeader}>Delete Header</button>
      </div>
    );
  }
}

class Child extends React.Component {
  componentWillUnmount() {
    alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}

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