在react 数据传递中经常使用的是经过props 进行数据传递,可是有的内容咱们是须要在整个页面中全部的组件使用的,这个时候若是还使用props一层一层的去去传递的话就比繁琐,怎么解决这个问题呢 react提供了一个 context
上下文来解决这个问题。若是使用了react-redux 进行react中组件之间数据传递的状况,基本是不会用到context 的。html
const MyContext = React.createContext(defaultValue);
建立一个context对象,当react render一个订阅了此context的组件的时候,他将从Provider中读取context中的值react
方法的第一个参数是defaultValue
参数只有在组件树种没有提供 Provider
组件时使用,这可使单独测试组件变得更方便些,注意:将undefined做为Provider值传递不会致使 consumer 组件使用defaultValue。git
<MyContext.Provider value={/* some value */}>
每个Context对象中都包含一个Provider组件,在Provider 上有一个value
属性,这个 value 属性将能被订阅(订阅有两种方式后面会说)了context 的后代组件直接获取,这样就能够避免props向深层级的组件传递的问题了,而且订阅了context的组件,当context的值放生变化的时候组件会自动从新rendergithub
这是一种订阅context内容的一种方法,在类的static属性contextType
设置为以前建立好的context
对象,在当前组件的各生命周期中使用 this.context
来访问上下文redux
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
也可使用app
class MyClass extends React.Component { static contextType = MyContext; render() { let value = this.context; /* render something based on the value */ } }
另外一种订阅context的方式就是使用 Comsumer
组件 ,Comsumer组件的子组件是一个函数,这个函数的第一个参数就是context 的值,函数的返回值必须是一个react 的 elementide
<MyContext.Consumer> {value => /* render something based on the context value */} </MyContext.Consumer>