Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. /*
  2. *
  3. * Parent.jsx
  4. *
  5. **/
  6. import React from 'react';
  7. import Child1 from './Child1';
  8.  
  9. export const RootContext = React.createContext();
  10.  
  11. export default class Parent extends React.Component {
  12. constructor(props) {
  13. super(props);
  14. this.state = {
  15. count: 0,
  16. }
  17. this.increase = this.increase.bind(this);
  18. }
  19. increase () {
  20. var c = this.state.count + 1;
  21. this.setState({count: c});
  22. }
  23. render(){
  24. return (
  25. <div className="App">
  26. <h1>親です。</h1>
  27. <h2>カウント情報を保持しています。(count = {this.state.count} <button onClick={this.increase}>+</button>)</h2>
  28. <RootContext.Provider value={{count: this.state.count, increase: this.increase}}>
  29. <Child1 />
  30. </RootContext.Provider>
  31. </div>
  32. );
  33. }
  34. }
  35.  
  36.  
  37. /*
  38. *
  39. * Child1.jsx
  40. *
  41. **/
  42. import React from 'react';
  43. import Child2 from './Child2';
  44.  
  45. export default class Child1 extends React.Component {
  46. render(){
  47. return (
  48. <div className="App">
  49. <h3>子1です</h3>
  50. <h4>アタシなんの値も貰ってません。</h4>
  51. <Child2 />
  52. </div>
  53. );
  54. }
  55. }
  56.  
  57.  
  58. /*
  59. *
  60. * Child2.jsx
  61. *
  62. **/
  63. import React from 'react';
  64. import { RootContext } from './Parent';
  65.  
  66. export default class Child2 extends React.Component {
  67. render(){
  68. return (
  69. <div className="App">
  70. <h5>子2です</h5>
  71. <RootContext.Consumer>
  72. {context=>
  73. <h6>アタシ親から直接情報もらいます。(count = {context.count} <button onClick={context.increase}>+</button>)</h6>
  74. }
  75. </RootContext.Consumer>
  76. </div>
  77. );
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement