为什么要采用context
公共信息(语言、主题)如何传递给每个组件?
用props太繁琐
用redux小题大做
context是react的一种组件之间的通讯方式,它不同于props。props需要逐层传递,当组件层数过多时,显得非常的麻烦。
Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。
API
React.createContext:创建一个上下文的容器(组件), defaultValue可以设置共享的默认数据
创建文件AllContext.js 导出
export default React.createContext('zhangsan');
Provider(生产者): 和他的名字一样。用于生产共享数据的地方。value:放置共享的数据。
App.jsx
import Context from './AllContext';
this.state = {
name: '张三'
}
<Context.Provider value={this.state.name}>
<span onClick={()=>this.setState({name:'li'})}>parent </span>
<hr/>
<Son></Son>
</Context.Provider>
Son不做任何操作,因为context不需要逐层进行传递
class Son extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (<div>
son
<hr />
<Grandson></Grandson>
</div>);
}
}
挂载在 class 上的 contextType 属性会被重赋值为一个由 React.createContext() 创建的 Context 对象。此属性能让你使用 this.context 来消费最近 Context 上的那个值。你可以在任何生命周期中访问到它,包括 render 函数中。
Son.jsx
Grandson.jsx
import React, { Component } from 'react';
import Context from './AllContext';
class Grandson extends Component {
static contextType = Context;
render() {
return (<div>
Grandson {this.context}
</div>);
}
}
export default Grandson;