React——context越级传值

我们都知道,在React中数据可以以流的形式自上而下的传递,当你使用组件的时候,你可以看到组件的props属性会自上而下传递。但是在有些情况下不想通过父组件的props属性一级一级的向下传递,而是希望在某一子级中直接得到上N级父组件的props中的值。那么接下来就让我们看一下通过props传值和context传值的情况

1、通过props传值

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>;
  }
}

过程解析:
(1)代码结构大致分为3级:顶层MessageList、Message一级子类和Button底层子类
(2)从父组件到子组件的传值情况——text:在顶层组件MessageList中的值,传递到一级子组件Message中,并在此组件中被使用{this.props.text}
(3)从父组件到子组件的传值情况——color:顶层组件MessageList中的值,先传递到一级子组件Message中,在传递到二级子组件Button中,最后在二级子组件中被使用{this.props.color}
(4)总结:从上边分析可以看出,通过props属性进行父子组件的传值是一级一级的向下传递的

2、通过context进行值得越级传递

class Button extends React.Component {
  render() {
    return (
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    );
  }
}
 
Button.contextTypes = {
  color: React.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: React.PropTypes.string
};

过程解析:
(1)在顶层组件MessageList中定义了顶层组件所拥有的子类context对象——该顶层组件所拥有的子类context对象为color,且必须为字符串,代码如下:

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

(2)通过getChldText方法,来给子context对象的属性赋值,这样就完成了顶层组件中,context组件的赋值,代码如下:

getChildContext() {
    return {color: "purple"};
}

(3)越级传递。因为color属性只在最底层使用(在一级子组件Message中并没有直接用到),因此可以直接传递到最底层(越级),在Button组件中使用。首先在Button组件中,再次说声明了所接受到的context的子组件color的类型,声明必须为字符串,代码如下:

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

(4)最后通过this.context.color这种方式调用,这样就通过Context实现了组件之间的越级传值,代码如下:

 <button style={{background: this.context.color}}>
     {this.props.children}
 </button>


作者:Julian小龙虾
链接:https://www.jianshu.com/p/4fa7323bc09e
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值