①跨组件通信
参考 :https://www.cnblogs.com/mengff/p/9511419.html
通过React.createContext
const MyContext = React.createContext(defaultValue);
下面是例子
import React, { Component } from 'react'
const MyContext = React.createContext();
class Son extends Component{
static contextType =MyContext
render (){
return (
<div>
<h3>这里是Son组件</h3>
<p>{ this.context }</p>
</div>
)
}
}
class Father extends Component{
render (){
return (
<div>
<h3>这里是father组件</h3>
<Son></Son>
</div>
)
}
}
class Grandfather extends Component {
constructor(){
super()
this.state={
num:1000,
}
}
render() {
return (
<div>
<h3>这里grandfather组件</h3>
<MyContext.Provider value = {this.state.num} >
<Father></Father>
</MyContext.Provider >
</div>
)
}
}
export default Grandfather
待续,后期在本文继续添加其他的组件通信