app.js

    1. import React from 'react';
    2. import Son from './components/son';//引入子组件
    3. // 创建一个 theme Context,
    4. export const {Provider,Consumer} = React.createContext("默认名称");
    5. export default class App extends React.Component {
    6. render() {
    7. let name ="我是需要共享的数据"
    8. return (
    9. //Provider共享容器 接收一个name属性
    10. <Provider value={name}>
    11. <div style={{border:'1px solid red',width:'30%',margin:'50px auto',textAlign:'center'}}>
    12. <p>父组件定义的值:{name}</p>
    13. <Son />
    14. </div>
    15. </Provider>
    16. );
    17. }
    18. }

    son.js

    1. //son.js 子类
    2. import React from 'react';
    3. import { Consumer } from "../../App";//引入父组件的Consumer容器
    4. import Grandson from "../grandson";//引入子组件
    5. function Son(props) {
    6. return (
    7. //Consumer容器,可以拿到上文传递下来的name属性,并可以展示对应的值
    8. <Consumer>
    9. {( name ) =>
    10. <div style={{ border: '1px solid blue', width: '60%', margin: '20px auto', textAlign: 'center' }}>
    11. <p>子组件。获取父组件的值:{name}</p>
    12. {/* 孙组件内容 */}
    13. <Grandson />
    14. </div>
    15. }
    16. </Consumer>
    17. );
    18. }
    19. export default Son;

    grandson.js

    1. //grandson.js 孙类
    2. import React from 'react';
    3. import { Consumer } from "../../App";//引入父组件的Consumer容器
    4. function Grandson(props) {
    5. return (
    6. //Consumer容器,可以拿到上文传递下来的name属性,并可以展示对应的值
    7. <Consumer>
    8. {(name ) =>
    9. <div style={{border:'1px solid green',width:'60%',margin:'50px auto',textAlign:'center'}}>
    10. <p>孙组件。获取传递下来的值:{name}</p>
    11. </div>
    12. }
    13. </Consumer>
    14. );
    15. }
    16. export default Grandson;