Component
Component は React コンポーネントの基底クラスであり、JavaScript のクラスとして定義されています。React は現在でもクラスコンポーネントをサポートしていますが、新しいコードでの使用は推奨されません。
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}- リファレンス
Componentcontextpropsstateconstructor(props)componentDidCatch(error, info)componentDidMount()componentDidUpdate(prevProps, prevState, snapshot?)componentWillMount()componentWillReceiveProps(nextProps)componentWillUpdate(nextProps, nextState)componentWillUnmount()forceUpdate(callback?)getSnapshotBeforeUpdate(prevProps, prevState)render()setState(nextState, callback?)shouldComponentUpdate(nextProps, nextState, nextContext)UNSAFE_componentWillMount()UNSAFE_componentWillReceiveProps(nextProps, nextContext)UNSAFE_componentWillUpdate(nextProps, nextState)static contextTypestatic defaultPropsstatic getDerivedStateFromError(error)static getDerivedStateFromProps(props, state)
- 使用法
- 代替案
リファレンス
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>
);
}
}