React 组件之间的通信(context上下文对象)

本文介绍如何使用 React 的 Context API 进行跨组件状态管理。通过两个实例详细讲解了单个及多个父组件如何向子组件传递数据,包括 Provider 和 Consumer 的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将Father 组件中的数据(状态数据或非状态数据) 传递给 Son1组件

context 上下文对象传值有两种方式:

1、

父组件发送数据: 父组件通过 Context 对象中 provider 属性 向指定的目标组件(Son1)传递指定的数据  value属性绑定传值对象(value名称不能随意修改)

目标组件(Son1)接收数据: 定义静态变量 static contextType ,将Context(FatherContext) 对象赋值赋值给contextType,再通过 this.context 进行 value 属性值接收

练习一:

Father.jsx:

import { Component } from 'react';

import Son from './Son';

import FatherContext from './FatherContext';


const { Provider } = FatherContext;

class Father extends Component {

  state = {
    person: {
      name: '张三',
      age: 300
    }
  }

  render() {
    return (
      <div>
        <h1>Father组件:</h1>
        <h3>{this.state.person.name} --- {this.state.person.age}</h3>
        <button onClick={this.handleAge.bind(this)}>修改person age</button>
        <hr/>
       {/*  <FatherContext.Provider value={{person: this.state.person, msg: 'Hello'}}>
          <Son/>
        </FatherContext.Provider> */}

        <Provider value={{person: this.state.person, msg: 'Hello'}}>
          <Son/>
        </Provider>
       
      </div>
    )
  }

  handleAge(){
    this.setState({
      person: {...this.state.person, age: new Date().getTime()}
    });
  }
}

export default Father;

FatherContext.js:

/* 
创建 Father 组件所需的 Context
 */

import { createContext } from 'react';

/* 
createContext(params) : 创建Context对象  params: 任意类型(基础类型、 引用类型) 给新建的Context对象设置默认值 在对应的组件中没有提供 Provider 则目标组件获取 默认值
*/
const FatherContext = createContext();

export default FatherContext;

Son.jsx:

import { Component } from 'react';

import Son1 from './Son1';

class Son extends Component {
  render() {
    return (
      <div>
        <h1>Son组件:</h1>
        <hr/>

        <Son1/>
      </div>
      
    )
  }
}

export default Son;

Son1.jsx:

import { Component } from 'react';

import FatherContext from './FatherContext';

class Son1 extends Component {

  // 指定静态 contextType 变量值为 接收上下文对象(FatherContext) 注:contextType不能随意修改
  // static contextType = FatherContext;

  render() {
    console.log('Son1 this.context=>', this.context);
    const { msg, person } = this.context;
    return (
      <div>
        <h1>Son1组件:</h1>
        <h4>msg: {msg}</h4>
         <h4>person: {person.name} --- {person.age}</h4>
      </div>
      
    )
  }
}

Son1.contextType = FatherContext;

export default Son1;

练习二:

将Father 组件中的数据(状态数据或非状态数据) 传递给 Son1组件

context 上下文对象传值有两种方式:

2、多个父组件 传值给子组件(Father、Son 同时传值给 Son1)

父组件发送数据: 父组件通过 Context 对象中 provider 属性 向指定的目标组件(Son1)传递指定的数据  value属性绑定传值对象(value名称不能随意修改)

目标组件(Son1)接收数据: 通过 Context 对象中提供的consumer 进行接收

Father.jsx

import { Component } from 'react';

import Son from './Son';

import FatherContext from './FatherContext';



const { Provider } = FatherContext;

class Father extends Component {

  state = {
   content: 'Hello Father',
  }

  render() {
    return (
      <div>
        <h1>Father组件:</h1>
       
        <hr/>
       {/*  <FatherContext.Provider>
          <Son/>
        </FatherContext.Provider> */}

        <Provider value={this.state.content}>
          <Son/>
        </Provider>
       
      </div>
    )
  }


}

export default Father;

FatherContext.js

/* 
创建 Father 组件所需的 Context
 */

import { createContext } from 'react';

/* 
createContext(params) : 创建Context对象  params: 任意类型(基础类型、 引用类型) 给新建的Context对象设置默认值 
*/
const FatherContext = createContext('Father Context默认值');

export default FatherContext;

Son.jsx

import { Component } from 'react';

import Son1 from './Son1';

import SonContext from './SonContext';

class Son extends Component {
  render() {
    return (
      <div>
        <h1>Son组件:</h1>
        <hr/>
        <SonContext.Provider value={'Hello Son'}>
          <Son1/>
        </SonContext.Provider>
        
      </div>
      
    )
  }
}

export default Son;

Son1.jsx

import { Component } from 'react';

import FatherContext from './FatherContext';
import SonContext from './SonContext';


/* 
目标组件(Son1) 接收多个Context 对象:

通过 Conext 对象 提供的consumer 属性接收
 */

class Son1 extends Component {

  
  render() {
    console.log('Son1 this.context=>', this.context);
   
    return (
      <div>
        <h1>Son1组件:</h1>
        
      {/*   <SonContext.Consumer>
          {
            function(sonValue){
              return (
                <h3 className="h3 text-danger">接收Son传递的值:{sonValue}</h3>
              )
            }
          }
        </SonContext.Consumer>

        <FatherContext.Consumer>
          {
            function(fatherValue){
              return (
                <h3 className="h3 text-danger">接收Father传递的值:{fatherValue}</h3>
              )
            }
          }
        </FatherContext.Consumer> */}

      {/*   <SonContext.Consumer>
          {
            sonValue =>  (
              <h3 className="h3 text-danger">接收Son传递的值:{sonValue}</h3>
            ) 
          }
        </SonContext.Consumer>

        <FatherContext.Consumer>
          {
            fatherValue =>  (
              <h3 className="h3 text-danger">接收Father传递的值:{fatherValue}</h3>
            )
          }
        </FatherContext.Consumer> */}

        <SonContext.Consumer>
          {
            sonValue =>  (
              <div>
                <h3 className="h3 text-danger">接收Son传递的值:{sonValue}</h3>
                <FatherContext.Consumer>
                {
                  fatherValue =>  (
                    <h3 className="h3 text-danger">接收Father传递的值:{fatherValue}</h3>
                  )
                }
              </FatherContext.Consumer>
            </div>
            ) 
          }
        </SonContext.Consumer>

       

      </div>
      
    )
  }
}

export default Son1;

SonContext.js


import {createContext} from 'react';


const SonContext = createContext('Son Context 默认值');

export default SonContext;

### React组件通信使用 Context API 实现数据共享 #### 创建上下文对象 为了使不同层级的组件能够访问相同的数据,在最外层定义并导出一个上下文对象是必要的。这可以通过调用 `React.createContext()` 来完成,它会返回一个新的上下文对象。 ```javascript import React from 'react'; // 定义默认值为空的对象 const MyContext = React.createContext({}); export default MyContext; ``` 此部分代码创建了一个名为 `MyContext` 的上下文实例[^1]。 #### 提供者模式分发状态 接着,在应用的根部或任何希望作为数据源的位置包裹 `<MyContext.Provider>` 组件,并向其传递 `value` 属性来指定要共享的状态。 ```jsx import React, { useState } from 'react'; import MyContext from './path/to/MyContext'; // 导入之前创建好的context文件路径 function App() { const [data, setData] = useState('Initial Data'); return ( <MyContext.Provider value={{ data, setData }}> {/* 子组件 */} </MyContext.Provider> ); } ``` 这段代码展示了如何利用 `Provider` 将应用程序中的某些特定信息暴露给后代节点,使得这些节点可以方便地读取到该信息而不必担心中间层次结构的影响[^2]。 #### 消费者模式接收状态 最后一步是在目标子组件内部通过 `useContext(MyContext)` 钩子函数订阅来自父级提供的最新状态更新。 ```jsx import React, { useContext } from 'react'; import MyContext from './path/to/MyContext'; function ChildComponent() { const { data, setData } = useContext(MyContext); function handleClick() { setData('Updated Data'); } return ( <> <p>{data}</p> <button onClick={handleClick}>Update Data</button> </> ); } export default ChildComponent; ``` 上述例子说明了怎样在一个较深嵌套级别的组件里轻松获取由祖先级别所提供的公共资源,从而简化了复杂界面间的交互逻辑处理过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值