关于react Context的理解
react中Contex设计的目的是为了创建在组件树中能够共享的数据,子组件获取父组件数据无需通过props的层层传递
// react创建Context,通过createContext方法创建context对象,方法中参数为context对象的默认值
context MyContext = React.createContext(defauleValue)
// 下方为顶层组件App,在顶层组件使用Provider将数据放出
function App() {
// 需要全局共享的数据
const color = 'blue'
return (
// 使用创建的context对象的Provider元素,并将需要传递的数据放入value属性中
// 当Provider中的value属性值发生变化时,它内部所有的消费组件都会重新渲染
<MyContext.Provider value={color}>
<Son />
</MyContext.Provider>
)
}
中间子组件
class Son extends React.Component{
render() {
return (
<GrandSon />
)
}
}
孙组件,想要接收顶层组件放出的数据有两种方式
方式一:使用Consumer接收
class GrandSon extends React.Component{
render() {
return (
<MyContext .Consumer>
{(color) => (
<div>
<button>{color}</button>
</div>
)}
</MyContext .Consumer>
)
}
}
方式二:使用contextType属性接收
class GrandSon extends React.Component{
// 指定contextType读取MyContext,React会顺着组件树往上找到最近的Provider,然后使用它的值
static contextType = MyContext
render() {
return (
<button>{this.context}</button>
)
}
}