react context 学习

在react 数据传递中常用的是通过props 进行数据传递,但是有的内容我们是需要在整个页面中所有的组件使用的,这个时候如果还使用props一层一层的去去传递的话就比繁琐,怎么解决这个问题呢 react提供了一个 context 上下文来解决这个问题。如果使用了react-redux 进行react中组件之间数据传递的情况,基本是不会用到context 的。

React.createContext

const MyContext = React.createContext(defaultValue);
复制代码

创建一个context对象,当react render一个订阅了此context的组件的时候,他将从Provider中读取context中的值

方法的第一个参数是defaultValue 参数只有在组件树种没有提供 Provider组件时使用,这可以使单独测试组件变得更方便些,注意:将undefined作为Provider值传递不会导致 consumer 组件使用defaultValue。

Context.Provider

<MyContext.Provider value={/* some value */}>
复制代码

每一个Context对象中都包含一个Provider组件,在Provider 上有一个value 属性,这个 value 属性将能被订阅(订阅有两种方式后面会说)了context 的后代组件直接获取,这样就可以避免props向深层级的组件传递的问题了,并且订阅了context的组件,当context的值放生变化的时候组件会自动重新render

Class.contextType

这是一种订阅context内容的一种方法,在类的static属性contextType设置为之前创建好的context对象,在当前组件的各生命周期中使用 this.context 来访问上下文

class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* perform a side-effect at mount using the value of MyContext */
  }
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  }
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  }
  render() {
    let value = this.context;
    /* render something based on the value of MyContext */
  }
}
MyClass.contextType = MyContext;
复制代码

如果你使用了 public class fields syntax 也可以使用

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}
复制代码

Context.Consumer

另一种订阅context的方式就是使用 Comsumer 组件 ,Comsumer组件的子组件是一个函数,这个函数的第一个参数就是context 的值,函数的返回值必须是一个react 的 element

<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>
复制代码

官方文档
自己写的小demo

转载于:https://juejin.im/post/5cf7835ff265da1b5e72e270

猜你喜欢

转载自blog.csdn.net/weixin_33922670/article/details/91470726
今日推荐