React

012|React之Context

2017-06-07  本文已影响33人  中年小钢炮

假设有层级 A->B->C->D,如果A需要传递一个参数给D,根据前文的知识,只能通过props参数一层一层传递。

有没有更便捷的方法呢?React提供了context机制来解决这个问题。
context涉及到父级(发送方)和子级(接收方),父级设置context,子级读取context。

我们先来看一下父级的一个实现:

class MessageList extends React.Component {
  getChildContext() {
    return {color: "purple"};
  } // 此具返回childContext具体值

  render() {
    const children = this.props.messages.map((message) =>
      <Message text={message.text} />
    );
    return <div>{children}</div>;
  }
}

MessageList.childContextTypes = {  // 通过childContextTypes定义context中变量类型
  color: PropTypes.string
};

父级通过childContextType来定义context中的类型,以及通过getChildContext来返回context的具体value。

再来看一下子级如何获取父级设置的context:

class Button extends React.Component {
  render() {
    return (
      <button style={{background: this.context.color}}> // 使用context
        {this.props.children}
      </button>
    );
  }
}

Button.contextTypes = { // 定义接收context
  color: PropTypes.string
};

子级通过contextTypes来标识自己接收context,然后就能直接使用context了。
如果子级没有定义contextTypes,则context对象将为空。另外,如果定义了contextTypes,以下回调中都会添加一个新参数context参数:

constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)
componentDidUpdate(prevProps, prevState, prevContext)

最后,函数式组件中,通过定义contextType也能使用context:

const PropTypes = require('prop-types');

const Button = ({children}, context) =>
  <button style={{background: context.color}}>
    {children}
  </button>;

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

因为函数式组件不支持state、ref,一般不建议使用函数式组件。

想学计算机技术吗?需要1对1专业级导师指导吗?想要团队陪你一起进步吗?欢迎加我为好友!微信号:iTekka。

上一篇下一篇

猜你喜欢

热点阅读