How To Use Context
不使用context 使用contextBy 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将为空对象。
网友评论