クラス構文は、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になります。したがって、この例はあまり役に立ちません。 それは私たちを…
ライフサイクルフックの使用
クラスコンポーネントは、コンポーネントのライフサイクル中に実行される関数を定義できます。 ライフサイクルメソッドには、componentWillMount
、componentDidMount
、componentWillReceiveProps
、shouldComponentUpdate
、componentWillUpdate
、componentDidUpdate
の合計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.setState
はrender
では使用できません。