内容简介:在react 数据传递中常用的是通过props 进行数据传递,但是有的内容我们是需要在整个页面中所有的组件使用的,这个时候如果还使用props一层一层的去去传递的话就比繁琐,怎么解决这个问题呢 react提供了一个创建一个context对象,当react render一个订阅了此context的组件的时候,他将从Provider中读取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>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 一文读懂监督学习、无监督学习、半监督学习、强化学习这四种深度学习方式
- 学习:人工智能-机器学习-深度学习概念的区别
- 统计学习,机器学习与深度学习概念的关联与区别
- 混合学习环境下基于学习行为数据的学习预警系统设计与实现
- 学习如何学习
- 深度学习的学习历程
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Head First Web Design
Ethan Watrall、Jeff Siarto / O’Reilly Media, Inc. / 2009-01-02 / USD 49.99
Want to know how to make your pages look beautiful, communicate your message effectively, guide visitors through your website with ease, and get everything approved by the accessibility and usability ......一起来看看 《Head First Web Design》 这本书的介绍吧!