React Context用法总结

Context做用

React中,父子组件通讯的机制,父子组件的通讯是经过props进行数据的传递。
Context提供了一种方式,可以让数据跨越组件层级来传递,再也不须要一层一层的传递html

如何使用

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对象进行使用react

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...)也但愿帮助到须要的小伙伴们。ide

相关文章
相关标签/搜索