落とし穴

クラスの代わりに関数でコンポーネントを定義することを推奨します。移行方法はこちら

Component は React コンポーネントの基底クラスであり、JavaScript のクラスとして定義されています。React は現在でもクラスコンポーネントをサポートしていますが、新しいコードでの使用は推奨されません。

class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

リファレンス

Component

クラスとして React コンポーネントを定義するには、組み込みの Component クラスを継承し、render メソッドを定義します。

import { Component } from 'react';

class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

render メソッドのみが必須です。他のメソッドはオプションです。

さらに例を見る


context

クラスコンポーネントではコンテクストthis.context の形で利用できます。これは、static contextType を使用して受け取りたいコンテクストを指定した場合にのみ利用できます。

クラスコンポーネントは、一度に 1 種類のコンテクストしか読み取ることができません。

class Button extends Component {
static contextType = ThemeContext;

render() {
const theme = this.context;
const className = 'button-' + theme;
return (
<button className={className}>
{this.props.children}
</button>
);
}
}

補足

クラスコンポーネントで this.context を読み取ることは、関数コンポーネントで