react之context 跨组件传递数据

在使用redux的过程中,我们在根组件注入store,然后想在所有的下级组件(包括子组件,孙组件……)去使用store,其中最容易想到的办法就是,将store从根组件一级一级向下传递,OK这种办法可以实现,但是对于嵌套了多级的组件来说,就显得有些麻烦了,比如根组件的第五级组件需要使用store去dispatch一个action,那么中间每一个组件都要传递store到下一级,即使他们并不需要使用.
那么有没有一种像是全局变量这种的方案呢,当然有, 就是 context 这个API
下面通过官网的例子讲解使用
1.这个为”一级一级向下传递的解决方案”
javascript 代码

import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Button extends React.Component {
  render() {
    return (
      <button style={{background: this.props.color}}>
        {this.props.children}
      </button>
    );
  }
}

class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button color={this.props.color}>Delete</Button>
      </div>
    );
  }
}

class MessageList extends React.Component {
  render() {
    const color = "purple";
    const children = this.props.messages.map((message) =>
      <Message text={message.text} color={color} />
    );
    return <div>{children}</div>;
  }
}

2.这个为context的解决方案
javascript 代码

import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Button extends React.Component {
  render() {
    return (
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    );
  }
}

Button.contextTypes = {
  color: PropTypes.string
};

class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button>Delete</Button>
      </div>
    );
  }
}

class MessageList extends React.Component {
  getChildContext() {
    return {color: "purple"};
  }

  render() {
    const children = this.props.messages.map((message) =>
      <Message text={message.text} />
    );
    return <div>{children}</div>;
  }
}

MessageList.childContextTypes = {
  color: PropTypes.string
};

getChildContext就是你希望向下级组件传递的东西,它用于根组件
childContextTypes 声明子组件作用域的类型,用于根组件
contextTypes 表明子组件的作用域类型,这与 childContextTypes 相当于一个接口暗号,如果对上了,OK就可以使用根组件传过来的东西了.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值