Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- *
- * Parent.jsx
- *
- **/
- import React from 'react';
- import Child1 from './Child1';
- export const RootContext = React.createContext();
- export default class Parent extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- count: 0,
- }
- this.increase = this.increase.bind(this);
- }
- increase () {
- var c = this.state.count + 1;
- this.setState({count: c});
- }
- render(){
- return (
- <div className="App">
- <h1>親です。</h1>
- <h2>カウント情報を保持しています。(count = {this.state.count} <button onClick={this.increase}>+</button>)</h2>
- <RootContext.Provider value={{count: this.state.count, increase: this.increase}}>
- <Child1 />
- </RootContext.Provider>
- </div>
- );
- }
- }
- /*
- *
- * Child1.jsx
- *
- **/
- import React from 'react';
- import Child2 from './Child2';
- export default class Child1 extends React.Component {
- render(){
- return (
- <div className="App">
- <h3>子1です</h3>
- <h4>アタシなんの値も貰ってません。</h4>
- <Child2 />
- </div>
- );
- }
- }
- /*
- *
- * Child2.jsx
- *
- **/
- import React from 'react';
- import { RootContext } from './Parent';
- export default class Child2 extends React.Component {
- render(){
- return (
- <div className="App">
- <h5>子2です</h5>
- <RootContext.Consumer>
- {context=>
- <h6>アタシ親から直接情報もらいます。(count = {context.count} <button onClick={context.increase}>+</button>)</h6>
- }
- </RootContext.Consumer>
- </div>
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement