Context作用
React中,父子组件通信的机制,父子组件的通信是通过props进行数据的传递。
Context提供了一种形式,可能让数据逾越组件层级来传递,不再须要一层一层的传递
如何应用
React.createContext()
const MyContext = React.createContext(defaultValue) defaultValue 默认值,没有Provider时会失效
Context.Provider
<MyContext.Provider value={/* 某个值 */}>Provider 接管一个 value 属性,传递给生产组件
Class.contextType
能够通过Class.contextType间接将Context对象挂载到class的contextType属性,而后就能够应用this.context对context对象进行应用
class MyClass extends React.Component { render() { let value = this.context; /* 基于 MyContext 组件的值进行渲染 */ }}MyClass.contextType = MyContext;或class MyClass extends React.Component { static contextType = MyContext; render() { let value = this.context; /* 基于这个值进行渲染工作 */ }}
Context.Consumer
<MyContext.Consumer> {value => /* 基于 context 值进行渲染*/}</MyContext.Consumer>
置信小伙伴对 React context 的作用 以及应用有了肯定的理解。当然还有其余场景的应用,可间接看官网(https://react.docschina.org/d...)也心愿帮忙到须要的小伙伴们。