【React】—context用法

2017-12-19  本文已影响0人  南慕瑶

How To Use Context

不使用context 使用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.

如上代码,组件层级关系:

MessageList -> Message -> Button

父组件设置context:

定义 childContextTypes  getChildContext 。定义后,从这一层开始,所有的子组件都可以拿到定义的context。

子组件使用context:

定义 contextTypes 。定义后,才可以使用父组件中设置的context,否则,子组件读取的this.context将为空对象。

上一篇下一篇

猜你喜欢

热点阅读