如果两个组件是远房亲戚(比如:嵌套多层)可以使用Context实现组件通讯
Context组件提供了两个组件:Provider和Consumer
Provider组件:用来提供数据
Consumer组件:用来消费数据
const {Provider,Consumer} = Raect.createContext()
class Cpp extends React.Component{
state={
name='张子枫'
}
render(){
return(
<Provider value={this.state.name}>
<div><Node/></div>
</Provider>
)
}
}
const Node = () => {
return <div><Subnode/></div>
}
const Subnode = () => {
return<div><Child /></div>
}
const Child = ()=>{
return <div>
<Consumer>
{data => {<h1>我偶像的名字是:{data}</h1>}}
</Consumer>
</div>
}