app.js
import React from 'react';
import Son from './components/son';//引入子组件
// 创建一个 theme Context,
export const {Provider,Consumer} = React.createContext("默认名称");
export default class App extends React.Component {
render() {
let name ="我是需要共享的数据"
return (
//Provider共享容器 接收一个name属性
<Provider value={name}>
<div style={{border:'1px solid red',width:'30%',margin:'50px auto',textAlign:'center'}}>
<p>父组件定义的值:{name}</p>
<Son />
</div>
</Provider>
);
}
}
son.js
//son.js 子类
import React from 'react';
import { Consumer } from "../../App";//引入父组件的Consumer容器
import Grandson from "../grandson";//引入子组件
function Son(props) {
return (
//Consumer容器,可以拿到上文传递下来的name属性,并可以展示对应的值
<Consumer>
{( name ) =>
<div style={{ border: '1px solid blue', width: '60%', margin: '20px auto', textAlign: 'center' }}>
<p>子组件。获取父组件的值:{name}</p>
{/* 孙组件内容 */}
<Grandson />
</div>
}
</Consumer>
);
}
export default Son;
grandson.js
//grandson.js 孙类
import React from 'react';
import { Consumer } from "../../App";//引入父组件的Consumer容器
function Grandson(props) {
return (
//Consumer容器,可以拿到上文传递下来的name属性,并可以展示对应的值
<Consumer>
{(name ) =>
<div style={{border:'1px solid green',width:'60%',margin:'50px auto',textAlign:'center'}}>
<p>孙组件。获取传递下来的值:{name}</p>
</div>
}
</Consumer>
);
}
export default Grandson;