加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React 中 context 的使用

发布时间:2020-12-15 07:27:47 所属栏目:百科 来源:网络整理
导读:原文 https://segmentfault.com/a/1190000005356878 主题 React 引自个人博客 [走啊走的记录] - React 中 context 的使用 官方文档说明(英) 看了别人写的中文博客,再看了官方英文文档,发现还是官方文档讲的浅显易懂一些,看了之后,半翻译半理解地写了这

原文

引自个人博客 [走啊走的记录] - React 中 context 的使用

官方文档说明(英)

看了别人写的中文博客,再看了官方英文文档,发现还是官方文档讲的浅显易懂一些,看了之后,半翻译半理解地写了这篇博客,更易于新手理解。

介绍

context是在react @ 0.14版本以后发布的一个高级且实验性的功能,有可能在未来做出更改。不推荐频繁使用,如果使用的话尽量保持在小范围内并且避免直接使用context的 API,为了以后升级框架更加容易。

使用 Context 的原因

为了有时候想传递数据通过组件树,但是不想给每一层级的组件手动传递属性,那么context就能帮你"越级"传递数据到组件树中你想传递到的深层次组件。

有时候A组件为了给B组件中的C组件传递一个prop,而需要把参数在组件中传递两次才能最终将A组件中的prop传递给C组件

官方文档的示例代码如下

var Button = React.createClass({
  render: function() {
    return (
      <button style={{background: this.props.color}}> {this.props.children} </button>
    );
  }
});

var Message = React.createClass({
  render: div> {this.props.text} <Button color={this.props.color}>Delete</Button> </div>
    );
  }
});

var MessageList = React.createClass({
  render: var color = "purple";
    var children = this.props.messages.map(function(message) {
      return <Message text={message.text} color={color} />; }); return <div>{children}</div>; } });

使用 context 改进数据传递

现在我们使用context来完成参数的传递试试

var Button = React.createClass({
  // 必须指定context的数据类型
  contextTypes: {
    color: React.PropTypes.string
  },render: {{background: this.context.color}}> {this.props.children} </Button>Delete</var MessageList = React.createClass({
  //
  childContextTypes: {
    color: React.PropTypes.string
  },getChildContext: return {color: "purple"};
  },0)">{message.text} />; }); return <div>; } });

示例代码中通过添加childContextTypesgetChildContext()MessageListcontext的提供者),React 自动向下传递数据然后在组件树中的任意组件(也就是说任意子组件,在此示例代码中也就是Button)都能通过定义contextTypes访问context中的数据。

总结

指定数据并要将数据传递下去的父组件要定义getChildContext();想要接收到数据的子组件必须定义contextTypes来使用传递过来的context

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读