我們知道React的組件之間是相互獨立的,組件之間的通信可以方便數(shù)據(jù)的傳遞和交流,那么在組件之間的通信有以下三種方式咨跌,父組件向子組件傳遞,子組件向父組件傳遞硼婿,沒有嵌套關(guān)系之間的組件傳遞锌半。
-
父組件向子組件通信
之前我們說過React的數(shù)據(jù)流向是單向數(shù)據(jù)流,父組件向子組件是通過props的方式傳遞需要的信息寇漫。
-
子組件向父組件通信
在某些情況下刊殉,父組件需要知道子組件中的狀態(tài),那么子組件是如何將自己的狀態(tài)傳遞給父組件州胳。
利用回調(diào)函數(shù)的方式记焊。
在父組件中通過props傳遞事件函數(shù)給子組件,子組件在適當(dāng)?shù)臅r候通過props獲得到該事件函數(shù)并觸發(fā)栓撞。利用自定義事件遍膜。
-
跨級組件通信
前面兩種組件中通信的方法都是比較常見和易于理解的,那么跨級組件通信瓤湘,我們可以通過向更高層級傳遞props瓢颅,如果這樣做的話那么代碼會顯的不夠優(yōu)雅,而且易于混亂弛说。在React中挽懦,我們還可以通過context來實現(xiàn)跨級父子組件間通信。
import React, {Component} from 'react'
class ListItem extends Component {
constructor(props){
super(props)
}
static contextTypes = {
color: PropTypes.string
}
render() {
const {value} = this.props
return (
<li>
<span>{this.context.color}</span> //context中的color
</li>
)
}
}
class List extends Component {
constructor(props){
super(props)
}
static childContextTypes = {
color: PropTypes.string
}
getChildContext() {
return {
color: 'red'
}
}
render() {
const {list} = this.props
return (
<div>
<ul>
{
list.map((item, index) => {
<ListItem key={index} value={item.value}></ListItem>
})
}
</ul>
</div>
)
}
}
如上剃浇,可以看到并沒有給ListItem傳遞props巾兆,而是在父組件中定義ChildContext猎物,這樣從這一層開始的子組件都可以拿到定義的context虎囚。
context就類似一個全局變量角塑。