React之使用context传递数据

本文通过实战案例展示了如何使用 React 的 Context API 在组件间传递数据,避免了繁琐的逐级 props 传递,简化了跨层级组件间的通信。文章首先创建了一个提供数据的父组件,并在其中定义了 getChildContext 方法来传递数据,接着展示了如何在子孙组件中通过 contextTypes 接收这些数据。

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

react中当要从父组件给子孙组件传递数据时 如果用props传递 则需要一级一级传递 而如果用context时 则可以在父组件中加入getChildContext函数 并声明需要传递的数据 在需要接受到数据的组件中声明变量类型Test.contextTypes = {test : PropTypes.string} 

Example:

//父组件
import React, { Component,PropTypes } from 'react';
import Son from './Son';

class App extends Component {

  getChildContext() {
      return {test: "hello"};
  }

  render() {
      return (
          <div className="App" style={{border:'1px solid red',width:'30%',margin:'50px auto',textAlign:'center'}}>
              <p style={{padding:'0',margin:'0'}}>父组件</p>
              <Son/>
          </div>
      );
  }
}

App.childContextTypes = {
    test: PropTypes.string
};

export default App;

 

//子组件
import React, { Component,PropTypes } from 'react';
import Grandson from './Grandson';

class SubChildApp extends Component {
    render() {
        console.log('this.context',this.context);

        return (
            <div className="son" style={{border:'1px solid blue',width:'60%',margin:'50px auto',textAlign:'center'}}>
                <p>子组件,获取父组件的值:{this.context.test}</p>
                <Grandson/>
            </div>
        );
    }
}
SubChildApp.contextTypes = {
    test: PropTypes.string
};
export default SubChildApp;
//孙组件
import React, { Component,PropTypes } from 'react';
class App extends Component {
    render() {
        console.log('this.context:',this.context);
        return (
            <div className="son" style={{border:'1px solid green',width:'60%',margin:'50px auto',textAlign:'center'}}>
                <p>孙组件,获取传递下来的值:{this.context.test}</p>
            </div>
        );
    }
}
App.contextTypes = {
    test: PropTypes.string
};
export default App;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值