【React】—context用法

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将为空对象。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容