1.创建容器(写在全局)
const xxxContext = React.createContext();
2.子组件时,外面包裹xxxContext.Provider,通过value属性传递数据
<xxxContext.Provider value={{ name }}>
<Child></Child>
<Func></Func>
</xxxContext.Provider>
3.组件读取数据
// 仅适用于类组件 取值:this.context
class Child extends PureComponent {
static contextType = xxxContext;
render() {
console.log(this.context);
return (
<div className="child">
<h3>我是Child组件</h3>
</div>
);
}
}
// 类和函数组件都可以 取值:value
function Func() {
return (
<div className="three">
<h2>我是Func组件</h2>
<xxxContext.Consumer>
{
value => {
return `name:${value.name}`
}
}
</xxxContext.Consumer>
</div>
);
}