Context 的目的是对于全局的需要多处使用的数据,不希望通过 prop 一层层传递下去,而是可以直接使用。
childContextTypes & getChildContext
该方案在 16.3 后不再是推荐方案。
React 最初提供的 context 方案是提供 context 数据的组件通过静态的 childContextType 来定义 context 中各字段的数据类型,通过 getChildContext 成员方法来提供实际的 context 数据,其中,返回的数据可以搭配 prop 和 state 来提供响应式的数据。而消费 context 数据的组件通过静态的 contextTypes 来指定需要消费的 context 字段的类型集合,然后即可通过 this.context[fieldName] 来使用。
注意,消费 context 的组件只需要定义需要的字段的类型即可,不需要是全部。同时,也不需要是提供 context 的组件的直接子组件。
import PropTypes from 'prop-types';
class Button extends React.Component {
  static contextTypes = {
    color: PropTypes.string
  };
  render() {
    return (
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    );
  }
}
class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button>Delete</Button>
      </div>
    );
  }
}
class MessageList extends React.Component {
  static childContextTypes = {
    color: PropTypes.string
  };
  getChildContext() {
    return {color: "purple"};
  }
  render() {
    const children = this.props.messages.map((message) =>
      <Message text={message.text} />
    );
    return <div>{children}</div>;
  }
}