import { Component, createContext } from "react"
const { Provider, Consumer } = createContext()
// 函数式组件
function SonF () {
return (
<>
<div>我是SonF</div>
<SonC></SonC>
</>
)
}
// 类组件SonC
class SonC extends Component {
render () {
return (
<>
<Consumer>
{value => <div>我是类组件SonC{value}</div>}
</Consumer>
</>
)
}
}
class App extends Component {
state = {
msg: '我是App的数据'
}
render () {
return (
<Provider value={this.state.msg}>
<div>
<SonF></SonF>
</div>
</Provider>
)
}
}
export default App
React.js实现跨组件通信(createContext )
最新推荐文章于 2024-09-02 15:22:27 发布