晴明的博客园 GitHub      CodePen      CodeWars     

[react] context

By adding
childContextTypes
and
getChildContext
to MessageList (the context provider),
React passes the information down automatically and any component
in the subtree (in this case, Button) can access it by defining
contextTypes .
If contextTypes is not defined, then context will be an empty object.

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

Referencing Context in Lifecycle Methods

constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)
componentDidUpdate(prevProps, prevState, prevContext)
posted @ 2016-11-14 13:57  晴明桑  阅读(163)  评论(0编辑  收藏  举报