React之使用context传递数据

与props只能逐级传递数据相比,使用context可以实现跨级传递数据。
下面通过一个demo来展示context传递数据的实现:

//父组件,最上层的组件
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 App 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>
        );
    }
}
App.contextTypes = {
    test: PropTypes.string
};
export default App;
//孙组件
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;

最终实现效果如下图

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值