React Context用法总结

Context作用

React中,父子组件通信的机制,父子组件的通信是通过props进行数据的传递。
Context提供了一种方式,能够让数据跨越组件层级来传递,不再需要一层一层的传递

如何使用

React.createContext()
 const MyContext = React.createContext(defaultValue)
 defaultValue 默认值,没有Provider时会生效
Context.Provider

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

  {value => /* 基于 context 值进行渲染*/}

相信小伙伴对 React context 的作用 以及使用有了一定的了解。当然还有其他场景的使用,可直接看官网(https://react.docschina.org/d...)也希望帮助到需要的小伙伴们。

你可能感兴趣的:(react.js)