react中祖组件与后代组件通信(Context)

268 阅读1分钟

Context

理解

一种组件间通信方式, 常用于【祖组件】与【后代组件】间通信

使用

1) 创建Context容器对象:
	const XxxContext = React.createContext()  
	
2) 渲染子组时,外面包裹xxxContext.Provider, 通过value属性给后代组件传递数据:
	<xxxContext.Provider value={数据}>
		子组件
    </xxxContext.Provider>
    
3) 后代组件读取数据:

	//第一种方式:仅适用于类组件 
	  static contextType = xxxContext  // 声明接收context
	  this.context // 读取context中的value数据
	  
	//第二种方式: 函数组件与类组件都可以
	  <xxxContext.Consumer>
	    {
	      value => ( // value就是context中的value数据
	        要显示的内容
	      )
	    }
	  </xxxContext.Consumer>

注意

在应用开发中一般不用context, 一般都用它的封装react插件
import React, { Component } from 'react'

// 祖组件与后代组件通信使用Context

// 1.在所有组件外部定义公共的Context (使用函数式组件需要引入Consumer)
const myContext = React.createContext()
const { Provider, Consumer } = myContext

class B extends Component {
  render() {
    return (
      <div>
        <h1>我是B组件</h1>
        <h1>拿到A组件的数据是:</h1>
        <C />
      </div>
    )
  }
}

// class C extends Component {
//   // 3.在需要使用到context的后代组件中定义static属性,就可以拿到祖组件传递过来的数据
//   static contextType = myContext
//   render() {
//     return (
//       <div>
//         <h1>我是c组件</h1>
//         <h1>拿到A组件的数据是:{this.context.name}</h1>
//       </div>
//     )
//   }
// }

// 函数式组件使用context
function C() {
  return (
    <div>
      <h1>我是c组件</h1>
      <h1>
        <Consumer>
          {(value) => {
            return `拿到A组件的数据是:${value.name}`
          }}
        </Consumer>
      </h1>
    </div>
  )
}

export default class ContextDemo extends Component {
  render() {
    return (
      <>
        <h1>我是A组件</h1>
        {/* 2.使用Provider组件包裹需要使用context的子组件 */}
        <Provider value={{ name: 'aaa' }}>
          <B />
        </Provider>
      </>
    )
  }
}