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.
如上代碼全景,組件層級關(guān)系:
MessageList -> Message -> Button
父組件設(shè)置context:
定義 childContextTypes 和?getChildContext 。定義后,從這一層開始阱高,所有的子組件都可以拿到定義的context嫡良。
子組件使用context:
定義?contextTypes 倡勇。定義后饥脑,才可以使用父組件中設(shè)置的context阿蝶,否則诀艰,子組件讀取的this.context將為空對象柬甥。