《十二》组件通信之使用 Context 进行祖孙组件间通信

本文详细介绍了React的Context API,包括如何创建和使用Context对象,以及在祖先组件与后代组件间的数据传递。通过示例展示了类组件和函数组件中使用Context.Consumer接收数据的方法,并提到了Context的嵌套使用和默认值设置。强调了谨慎使用Context以避免降低组件复用性。

Context:提供了一种不需通过中间组件传递,就可以在组件之间共享数据的方式。常用于祖先组件与后代组件间通信。

总而言之:就是通过 React.createContext() 创建一个 Context 对象;祖先组件通过 Context.Provider 传递数据;后代组件通过 Context.Consumer 接收数据。需要谨慎使用,因为这会使得组件的复用性变差。

import React from 'react'
// 通过 React.createContext(defaultValue) 创建一个 Context 对象
const GrandparentContext = React.createContext()
export default GrandparentContext
// 祖先组件传递数据
// 引入 GrandparentContext 对象
import GrandparentContext from './context'
class Grandparent extends React.Component {
  render() {
     return (
    	<>
    		<h2>这是 Grandparent 组件</h2>
    		{/* 使用 Context.Provider 组件包裹想要共享数据的子组件,也可以直接简写为 Context。想要共享的数据通过 value 属性传递,value 属性名不能修改 */}
    		<GrandparentContext.Provider value={{username: 'Lee'}}>
    			<Parent />
    		</GrandparentContext.Provider>
    	</>
    )
  }
}
// 中间组件
class Parent extends React.Component {
  render() {
     return (
    	<>
    		<h2>这是 Parent 组件</h2>
    		<Child />
    	</>
    )
  }
}
// 后代组件读取数据方式一:类组件和函数组件都适用
// 引入 GrandparentContext 对象
import GrandparentContext from './context'
function Child() {
  return (
   <>
     <h2>这是 Child 组件</h2>
     {/* 使用 Context.Consumer 组件,里面是一个函数,函数接收到的参数就是传递过来的数据,返回值就是想要展示的内容 */}
     <GrandparentContext.Consumer>
      {
        value => {
          return <h4>这是从 Grandparent 组件中接收到的用户名:{value.username}</h4>
        }
      }
    </GrandparentContext.Consumer>
   </>
 )
}
// 后代组件读取数据方式二:只适用于类组件
// 引入 GrandparentContext 对象
import GrandparentContext from './context'
class Child extends React.Component {
   // 也可以使用静态属性的方式声明接收的是哪个 Context 对象
   // static contextType = GrandparentContext
   
   render() {
     return (
    	<>
    		<h2>这是 Child组件</h2>
    		<h4>这是从 Grandparent 组件中接收到的用户名:{this.context.username}</h4>
    	</>
    )
  }
}
// 声明接收的是哪个 Context 对象,声明接收之后,使用 this.context 可以在任何生命周期中获取到传递过来的数据
Child.contextType = GrandparentContext

Context 可以嵌套使用:

// 传递数据的祖先组件
<UserContext.Provider value={{name: 'Lee'}}>
  <ProfessionContext.Provider value={{profession: '学生'}}>
    <Parent />
  </ProfessionContext.Provider>
</UserContext.Provider>

// 接收数据的后代组件
<UserContext.Consumer>
  {
    value => {
        return <ProfessionContext.Consumer>
          {
            professionValue => {
              return <h4>{value.name} 的职业是: {professionValue.profession}</h4>
            }
          }
        </ProfessionContext.Consumer>
    }
  }
</UserContext.Consumer>

Context 的默认值:

组件并没有作为 Context.Provider 的后代元素,但是又想要使用 Context,此时可以获取到 Context 的默认值。

import React from 'react'
export default const GrandparentContext = React.createContext({name: 'Lee'})
// 祖先组件
class Grandparent extends React.Component {
  render() {
    return (
     <>
       <h2>这是 Grandparent 组件</h2>
       <Parent />
     </>
   )
 }
}
// 中间组件
class Parent extends React.Component {
  render() {
    return (
    	<>
    		<h2>这是 Parent 组件</h2>
    		<Child username={this.props.username} />
    	</>
    )
  }
}
// 后代组件
import {GrandparentContext} from './context'
class child extends React.Component {
  render() {
    return (
      <>
        <h2>这是 Child 组件</h2>
        <GrandparentContext.Consumer>
          {
            value => {
              return <h4>{value.name}</h4>
            }
          }
        </GrandparentContext.Consumer>
      </>
    )
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值