我們知道React的組件之間是相互獨(dú)立的,組件之間的通信可以方便數(shù)據(jù)的傳遞和交流,那么在組件之間的通信有以下三種方式,父組件向子組件傳遞,子組件向父組件傳遞,沒有嵌套關(guān)系之間的組件傳遞。
-
父組件向子組件通信
之前我們說過React的數(shù)據(jù)流向是單向數(shù)據(jù)流,父組件向子組件是通過props的方式傳遞需要的信息。
-
子組件向父組件通信
在某些情況下,父組件需要知道子組件中的狀態(tài),那么子組件是如何將自己的狀態(tài)傳遞給父組件。
利用回調(diào)函數(shù)的方式。
在父組件中通過props傳遞事件函數(shù)給子組件,子組件在適當(dāng)?shù)臅r(shí)候通過props獲得到該事件函數(shù)并觸發(fā)。利用自定義事件。
-
跨級(jí)組件通信
前面兩種組件中通信的方法都是比較常見和易于理解的,那么跨級(jí)組件通信,我們可以通過向更高層級(jí)傳遞props,如果這樣做的話那么代碼會(huì)顯的不夠優(yōu)雅,而且易于混亂。在React中,我們還可以通過context來實(shí)現(xiàn)跨級(jí)父子組件間通信。
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就類似一個(gè)全局變量。