context,一种组件间通信方式,常用于祖组件和后代组件。父子组件一般不使用。
在应用开发中一般不用context, 一般都用它的封装react插件,比如react-redux。
下图中A和C、D 通信就是祖和后代组件。父子可以用context,但是不常用,因为父子用props更简单。
1) 创建Context容器对象
注意:需要在祖、后代组件都可以访问到的位置定义context容器。
const XxxContext = React.createContext()2) 在祖组件定义子组件时,外面包裹xxxContext.Provider, 通过value属性定义值。此时子组件的后代组件就可以接收到数据
value可以是字符串,也可是对象。
<xxxContext.Provider value={数据}> 子组件 </xxxContext.Provider>注意:子组件包含后代组件,此时后代组件可以接收到context传值。
3) 后代组件读取数据
第一种方式 只有类组件能使用
static contextType = xxxContext // 声明接收context,名字必须是contextType
this.context // 读取context中的value数据
第二种方式 函数组件与类组件都可以使用Consumer里面是一个函数。单个接收值,如果单个返回值可以不写return和大括号。
<xxxContext.Consumer>
{
value => ( // value就是context中的value数据
要显示的内容
)
}
</xxxContext.Consumer>### 注意
在应用开发中一般不用context, 一般都用它的封装react插件,比如react-redux。
A B C D 四个组件,D是函数式组件,其他是类式组件。
- import React, { Component, Fragment } from 'react'
- import Demo from './05-context'
-
- //1.在祖 后代组件都可以访问的位置定义context容器
- const MyContext = React.createContext()
-
- const { Provider, Consumer } = MyContext
-
- export default class A extends Component {
- state = { name: "tom" }
- render() {
- return (
- //2.祖组件 定义子组件时 使用Provider包括
- <Provider value={"tom"}>
- <h3>我是A组件</h3>
- <p>我的用户名{this.state.name}</p>
- <B />
- </Provider>
- )
- }
- }
-
-
- class B extends Component {
- render() {
- return (
- <>
- <h3>我是B组件</h3>
- <p>我的用户名{"???"}</p>
- <C />
- </>
- )
- }
- }
-
-
- class C extends Component {
- //3. 如果后代组件是类组件 可以使用第一种方式接受context值
- static contextType = MyContext
- render() {
- return (
- <>
- <h3>我是C组件</h3>
- <p>我的用户名{this.context}</p>
- <D />
- </>
- )
- }
- }
-
- function D() {
-
- return (
- <>
- <h3>我是D组件</h3>
- //3. 如果后代组件是函数式组件 接受context可以使用Consumer
- <Consumer>{value => `我的用户名${value}`}
- </Consumer>
- </>
- )
-
- }