在React中使用context来传递属性

什么时候使用:

  当需要向子组件传递的属性特别多,并且层级很多的时候使用。

原因:

  当父组件需要向子组件传递很多属性,并且层级很多的时候,逐层手写参数是一件很繁琐的事情,利用context,父组件可以把所所有子组件需要的属性保存在context对象中,就解决了需要手动传递属性的问题

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

利用context传递属性

const PropTypes = require('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 };

两个必不可少的关键点:

1. 在顶层父组件 (MessageList) 添加 childContextTypes 和 getChildContext.

2. 在子组件定义 contextTypes,就可以通过 this.context 对象获取相应的属性。

两种写法的区别: 

1、用props传递属性时,底层组件依赖于中间组件进行属性传递。不能直接从顶层组件获取属性

2、利用context传递属性,底层组件可以直接获取顶层组件的属性,不依赖于中间组件。

优劣比较:

1、用props进行属性传递,数据流向清晰可见,但是中间组件必须把上级组件的属性传递给下级组件,显得不够清爽。

2、用context进行属性传递时,底层组件可以直接从顶层组件获取属性,但是数据流向不是太明了。

 

但在React官方文档中并不推荐使用context。是因为利用context进行数据传递的时候,数据的流向不容易一眼就看出来,所以,在组件属性不是很多,层级较少的时候,直接利用props进行传递就可以了,不建议使用context。

多数情况下,用props从父组件向子组件传递数据就可以了。

posted @ 2018-04-14 16:22  snn_宁宁  阅读(463)  评论(0编辑  收藏  举报