Reactのクラスコンポーネントの概要

提供:Dev Guides
移動先:案内検索

クラス構文は、Reactコンポーネントを定義する最も一般的な方法の1つです。 機能構文よりも冗長ですが、ライフサイクルフックの形でより多くの制御を提供します。

このガイドは、BabelがReact用に適切に構成されていることを前提としています。 create-react-app を使用している場合、これはすでに当てはまります。


クラスコンポーネントの作成

クラスコンポーネントの作成は非常に簡単です。 Componentを拡張し、render関数を持つクラスを定義するだけです。

// MyComponent.js
import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
    return (
      <div>This is my component.</div>
    );
  }
}

export default MyComponent;

そこから、他のコンポーネントで使用できます。

// MyOtherComponent.js
import React, { Component } from 'react';
import MyComponent from './MyComponent';

class MyOtherComponent extends Component {
  render() {
    return (
      <div>
        <div>This is my other component.</div>
        <MyComponent />
      </div>
    );
  }
}

export default MyOtherComponent;

ファイルごとに1つのコンポーネントを定義する必要はありませんが、おそらくそれは良い考えです。


小道具の使用

現状では、MyComponentはそれほど有用ではありません。 常に同じものをレンダリングします。 幸い、Reactを使用すると、HTML属性に似た構文で小道具をコンポーネントに渡すことができます。

<MyComponent myProp="This is passed as a prop." />

その後、this.propsを使用して小道具にアクセスできます。

class MyComponent extends Component {
  render() {
    const {myProp} = this.props;
    return (
      <div>{myProp}</div>
    );
  }
}

角かっこで囲まれた変数は文字列としてレンダリングされます。


状態を使用する

クラスコンポーネントが機能コンポーネントよりも優れている点の1つは、コンポーネントの状態にアクセスできることです。

class MyComponent extends Component {
  render() {
    const {myState} = this.state || {};
    const message = `The current state is ${myState}.`;
    return (
      <div>{message}</div>
    );
  }
}

ただし、どこにも設定されていないため、this.stateはnullになるため、この例はあまり役に立ちません。 それは私たちを…

ライフサイクルフックの使用

クラスコンポーネントは、コンポーネントのライフサイクル中に実行される関数を定義できます。 ライフサイクルメソッドには、componentWillMountcomponentDidMountcomponentWillReceivePropsshouldComponentUpdatecomponentWillUpdatecomponentDidUpdateの合計7つがあります。 、およびcomponentWillUnmount。 簡潔にするために、1つだけを示します。

class MyComponent extends Component {
  // Executes after the component is rendered for the first time
  componentDidMount() {
    this.setState({myState: 'Florida'});
  }

  render() {
    const {myState} = this.state || {};
    const message = `The current state is ${myState}.`;
    return (
      <div>{message}</div>
    );
  }
}

this.stateを直接割り当てないでください。 代わりにthis.setStateを使用してください。


this.setStaterenderでは使用できません。