前言
注意: 從
React v15.5
開始 ,React.PropTypes 助手函數
已被棄用,我們建議使用prop-types 庫
來定義contextTypes
。
首先你需要通過在終端npm install prop-types
安裝一個叫prop-types的第三方包
context分為新版后舊版,這里都介紹下
一 context舊版使用步驟
1.1 根組件childContextTypes屬性
定義靜態屬性
getChildContext 指定的傳遞給子組件的屬性需要先通過 childContextTypes 來指定,不然會產生錯誤
// 聲明Context對象屬性
static childContextTypes = {
propA: PropTypes.string,
visibleA:PropTypes.string,
methodA: PropTypes.func
}
1.2 根組件getChildContext方法
返回context對象, 指定子組件可以使用的信息
// 返回Context對象,方法名是約定好的
getChildContext () {
return {
propA: this.state.propA,
methodA: this.changeStateByChildren
}
}
注意:如果context的值是動態的采用state管理,更改某個context值時,改變根組件的state
1.3 子組件contextTypes靜態屬性
調用context先定義靜態屬性,根據約定好的參數類型,否則會出現未定義
子組件需要通過 contextTypes
指定需要訪問的元素。 contextTypes 沒有定義, context 將是一個空對象。
static contextTypes = {
propA: PropTypes.string,
methodA:PropTypes.func
}
1.4 下文改變context的值,通過context的函數去改變根組件的狀態即可
新版context的使用步驟和方法:更好的解釋了生產者和消費者模式
1.5 例子
父組件Greeter
class Greeter extends Component {
constructor(props) {
super(props);
this.state = {
add: 87,
remove: 88,
};
}
static childContextTypes = {
add: PropTypes.number,
remove: PropTypes.number,
}
getChildContext() {
const { add, remove } = this.state;
return {
add,
remove,
};
}
render() {
return (
<div>
<ComponetReflux />
</div>
);
}
}
子組件ComponetReflux
class ComponetReflux extends Component {
constructor(props) {
super(props);
this.state = {
};
}
static contextTypes = {
add: PropTypes.number,
remove: PropTypes.number,
}
render() {
console.log(this.context); // 打印{add:87,remove:88}
const { name, age } = this.state;
return (
<div>測試context</div>
);
}
}
二 新版context的使用步驟和方法
更好的解釋了生產者和消費者模式
2.1 先定義全局context對象
import React from 'react'
const GlobalContext = React.createContext()
export default GlobalContext
2.2 根組件引入GlobalContext,並使用GlobalContext.Provider(生產者)
<GlobalContext.Provider
value={{
background: 'green',
color: 'white',
content:this.state.content,
methodA:this.changeStateByChildren
}}
/>
注意:傳入的value為根context對象的值,如果是動態的,使用狀態管理
2.3 子組件引入GlobalContext並調用context,使用GlobalContext.Consumer(消費者)
<GlobalContext.Consumer>
{
context => {
return (
<div>
<h1 style={{background: context.background, color: context.color}}>
{context.content}
</h1>
<Input methodA = {context.methodA} value={context.content}></Input>
</div>
)
}
}
</GlobalContext.Consumer>
注意:GlobalContext.Consumer內必須是回調函數
,改變context,通過context方法改變根組件狀態
三 context優缺點:
優點:跨組件訪問數據
缺點:react組件樹種某個上級組件shouldComponetUpdate 返回false,當context更新時,不會引起下級組件更新