ReactのContext APIを利用してコンポーネント間の情報を共有
ReactのContext APIはコンポーネント間でステートを共有するための機能です。
React.createContext();でContextを作成して<MyContext.Provider>で管理するステートや更新手法を定義して<MyContext.Consumer>で取得して利用できます。
import React from 'react';
const MyContext = React.createContext();
class App extends React.Component {
constructor(props){
super(props)
this.state = {
count:0
}
}
increment = () => {
this.setState({
count: this.state.count + 1
});
}
decrement = () => {
this.setState({
count: this.state.count - 1
});
}
render(){
return (
<MyContext.Provider
value={{
count: this.state.count,
increment: this.increment,
decrement: this.decrement
}}
>
<ChildComponent />
</MyContext.Provider>
)
}
}
// ただのコンポーネント
const ChildComponent = () => (
<div>
<ChildChildComponent1 />
<hr />
<ChildChildComponent2 />
</div>
)
const ChildChildComponent1 = () => (
<MyContext.Consumer>
{({count,increment}) => (
<>
count:{count} :
<input type="button" onClick={increment} value="+" />
</>
)}
</MyContext.Consumer>
)
const ChildChildComponent2 = () => (
<MyContext.Consumer>
{({count,decrement}) => (
<>
count:{count} :
<input type="button" onClick={decrement} value="-" />
</>
)}
</MyContext.Consumer>
)
export default App;
スポンサードリンク
«株式会社トゥーアールの2018年を振り返る | メイン | ReactのSyntheticEventとDebounce»