Reactガイドを読んでいくその35

これは

Reactのガイドを読んでいく記事です。

ガイドのリンク

ja.reactjs.org

コンテクスト

昨日の続き

API

React.createContext

その名の通りコンテクストオブジェクトを作成する。
Reactがコンテクストオブジェクトが登録されているコンポーネントをレンダーする場合最も近い上位の一致するProviderから現在のコンテクスト値を読み取る。

const MyContext = React.createContext(defaultValue);

Context.Provider

すべてのコンテクストオブジェクトにはプロバイダコンポーネントが付属している。
そのためコンシューマコンポーネントはコンテクストの変更を追うことができる。
valueプロパティを受け取り、子のコンシューマコンポーネントに渡される。

<MyContext.Provider value={/* 何らかの値 */}>

Class.contextType

React.createContext()によって作成されたコンテキストオブジェクトを指定することができる。
this.contextを使って、コンテクストタイプの最も近い現在値を利用することが可能。
レンダー関数を含むあらゆるライフサイクルメソッドで参照することができる。

class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* MyContextの値を使用し、マウント時に副作用を実行します */
  }
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  }
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  }
  render() {
    let value = this.context;
    /* MyContextの値に基づいて何かをレンダーします */
  }
}
MyClass.contextType = MyContext;
class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* 値に基づいて何かをレンダーします */
  }
}

Context.Consumer

コンテクストの変更を追うReactコンポーネント
関数コンポーネント内でコンテクストを追うことができる。

利用の場合はfunction as a childが必要。
コンテクストの値を受け取り、Reactノードを返す。

<MyContext.Consumer>
  {value => /* コンテクストの値に基づいて何かをレンダーします */}
</MyContext.Consumer>

Context.displayName

コンテクストオブジェクトはdisplayNameという文字列型のプロパティを有する。
ReactDevToolsはこの文字列を利用してコンテクストの表示の仕方を決定する。

const MyContext = React.createContext(/* some value */);
MyContext.displayName = 'MyDisplayName';

<MyContext.Provider> // "MyDisplayName.Provider" in DevTools
<MyContext.Consumer> // "MyDisplayName.Consumer" in DevTools

明日は例です。

今日はここまで。