react摸索之context

使用react过程中,经常有深层组件需要祖先组件的数据,但是中间层组件又不需要care这些数据,所以层级传递数据显得啰嗦,当然使用redux的话可以很明确的解决这个问题,本文讲述在不使用状态管理机的情况下的react的解决方法之——contex。并且在v16.3的react也会正式推出context的使用。

v16.3版本之前的contex一直被人诟病,而且官方文档也是三令五申谨慎使用contex。

Why Not To Use Contextarrow-up-right

而且用了context会违背redux单向管理数据流的理念。并且还会导致shouldComponentUpdate失效。

context的使用姿势:

import PropTypes from '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
};

VS

16.3的context:

那以后是不是就遍地的context.Provider了。。 摆不摆脱redux再研究吧。

参考: 0002-new-version-of-contextarrow-up-right React 16.3来了:带着全新的Context APIarrow-up-right Contextarrow-up-right

Last updated