關(guān)于react中組件通信的幾種方式詳解
前言
剛?cè)腴TReact可能會(huì)因?yàn)镽eact的單向數(shù)據(jù)流的特性而遇到組件間溝通的麻煩,下面這篇文章就來(lái)給大家詳細(xì)介紹下,在開始之前先來(lái)看一張圖:

react組件通信
- 需要組件之進(jìn)行通信的幾種情況
- 父組件向子組件通信
- 子組件向父組件通信
- 跨級(jí)組件通信
- 沒(méi)有嵌套關(guān)系組件之間的通信
1. 父組件向子組件通信
React數(shù)據(jù)流動(dòng)是單向的,父組件向子組件通信也是最常見(jiàn)的;父組件通過(guò)props向子組件傳遞需要的信息
Child.jsx
import React from 'react';
import PropTypes from 'prop-types';
export default function Child({ name }) {
return <h1>Hello, {name}</h1>;
}
Child.propTypes = {
name: PropTypes.string.isRequired,
};
Parent.jsx
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
render() {
return (
<div>
<Child name="Sara" />
</div>
);
}
}
export default Parent;
2. 子組件向父組件通信
- 利用回調(diào)函數(shù)
- 利用自定義事件機(jī)制
回調(diào)函數(shù)
實(shí)現(xiàn)在子組件中點(diǎn)擊隱藏組件按鈕可以將自身隱藏的功能
List3.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class List3 extends Component {
static propTypes = {
hideConponent: PropTypes.func.isRequired,
}
render() {
return (
<div>
哈哈,我是List3
<button onClick={this.props.hideConponent}>隱藏List3組件</button>
</div>
);
}
}
export default List3;
App,jsx
import React, { Component } from 'react';
import List3 from './components/List3';
export default class App extends Component {
constructor(...args) {
super(...args);
this.state = {
isShowList3: false,
};
}
showConponent = () => {
this.setState({
isShowList3: true,
});
}
hideConponent = () => {
this.setState({
isShowList3: false,
});
}
render() {
return (
<div>
<button onClick={this.showConponent}>顯示Lists組件</button>
{
this.state.isShowList3 ?
<List3 hideConponent={this.hideConponent} />
:
null
}
</div>
);
}
}
觀察一下實(shí)現(xiàn)方法,可以發(fā)現(xiàn)它與傳統(tǒng)回調(diào)函數(shù)的實(shí)現(xiàn)方法一樣.而且setState一般與回調(diào)函數(shù)均會(huì)成對(duì)出現(xiàn),因?yàn)榛卣{(diào)函數(shù)即是轉(zhuǎn)換內(nèi)部狀態(tài)是的函數(shù)傳統(tǒng);
3. 跨級(jí)組件通信
層層組件傳遞props
例如A組件和B組件之間要進(jìn)行通信,先找到A和B公共的父組件,A先向C組件通信,C組件通過(guò)props和B組件通信,此時(shí)C組件起的就是中間件的作用
使用context
context是一個(gè)全局變量,像是一個(gè)大容器,在任何地方都可以訪問(wèn)到,我們可以把要通信的信息放在context上,然后在其他組件中可以隨意取到;
但是React官方不建議使用大量context,盡管他可以減少逐層傳遞,但是當(dāng)組件結(jié)構(gòu)復(fù)雜的時(shí)候,我們并不知道context是從哪里傳過(guò)來(lái)的;而且context是一個(gè)全局變量,全局變量正是導(dǎo)致應(yīng)用走向混亂的罪魁禍?zhǔn)?
使用context
下面例子中的組件關(guān)系: ListItem是List的子組件,List是app的子組件
ListItem.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class ListItem extends Component {
// 子組件聲明自己要使用context
static contextTypes = {
color: PropTypes.string,
}
static propTypes = {
value: PropTypes.string,
}
render() {
const { value } = this.props;
return (
<li style={{ background: this.context.color }}>
<span>{value}</span>
</li>
);
}
}
export default ListItem;
List.jsx
import ListItem from './ListItem';
class List extends Component {
// 父組件聲明自己支持context
static childContextTypes = {
color: PropTypes.string,
}
static propTypes = {
list: PropTypes.array,
}
// 提供一個(gè)函數(shù),用來(lái)返回相應(yīng)的context對(duì)象
getChildContext() {
return {
color: 'red',
};
}
render() {
const { list } = this.props;
return (
<div>
<ul>
{
list.map((entry, index) =>
<ListItem key={`list-${index}`} value={entry.text} />,
)
}
</ul>
</div>
);
}
}
export default List;
app.jsx
import React, { Component } from 'react';
import List from './components/List';
const list = [
{
text: '題目一',
},
{
text: '題目二',
},
];
export default class App extends Component {
render() {
return (
<div>
<List
list={list}
/>
</div>
);
}
}
4. 沒(méi)有嵌套關(guān)系的組件通信
使用自定義事件機(jī)制
在componentDidMount事件中,如果組件掛載完成,再訂閱事件;在組件卸載的時(shí)候,在componentWillUnmount事件中取消事件的訂閱;
以常用的發(fā)布/訂閱模式舉例,借用Node.js Events模塊的瀏覽器版實(shí)現(xiàn)
使用自定義事件的方式
下面例子中的組件關(guān)系: List1和List2沒(méi)有任何嵌套關(guān)系,App是他們的父組件;
實(shí)現(xiàn)這樣一個(gè)功能: 點(diǎn)擊List2中的一個(gè)按鈕,改變List1中的信息顯示
首先需要項(xiàng)目中安裝events 包:
npm install events --save
在src下新建一個(gè)util目錄里面建一個(gè)events.js
import { EventEmitter } from 'events';
export default new EventEmitter();
list1.jsx
import React, { Component } from 'react';
import emitter from '../util/events';
class List extends Component {
constructor(props) {
super(props);
this.state = {
message: 'List1',
};
}
componentDidMount() {
// 組件裝載完成以后聲明一個(gè)自定義事件
this.eventEmitter = emitter.addListener('changeMessage', (message) => {
this.setState({
message,
});
});
}
componentWillUnmount() {
emitter.removeListener(this.eventEmitter);
}
render() {
return (
<div>
{this.state.message}
</div>
);
}
}
export default List;
List2.jsx
import React, { Component } from 'react';
import emitter from '../util/events';
class List2 extends Component {
handleClick = (message) => {
emitter.emit('changeMessage', message);
};
render() {
return (
<div>
<button onClick={this.handleClick.bind(this, 'List2')}>點(diǎn)擊我改變List1組件中顯示信息</button>
</div>
);
}
}
APP.jsx
import React, { Component } from 'react';
import List1 from './components/List1';
import List2 from './components/List2';
export default class App extends Component {
render() {
return (
<div>
<List1 />
<List2 />
</div>
);
}
}
自定義事件是典型的發(fā)布訂閱模式,通過(guò)向事件對(duì)象上添加監(jiān)聽(tīng)器和觸發(fā)事件來(lái)實(shí)現(xiàn)組件之間的通信
總結(jié)
- 父組件向子組件通信: props
- 子組件向父組件通信: 回調(diào)函數(shù)/自定義事件
- 跨級(jí)組件通信: 層層組件傳遞props/context
- 沒(méi)有嵌套關(guān)系組件之間的通信: 自定義事件
在進(jìn)行組件通信的時(shí)候,主要看業(yè)務(wù)的具體需求,選擇最合適的;
當(dāng)業(yè)務(wù)邏輯復(fù)雜到一定程度,就可以考慮引入Mobx,Redux等狀態(tài)管理工具
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
參考
相關(guān)文章
react 通過(guò)后端接口實(shí)現(xiàn)路由授權(quán)的示例代碼
本文主要介紹了React應(yīng)用中通過(guò)后端接口獲取路由授權(quán),實(shí)現(xiàn)動(dòng)態(tài)和靈活的權(quán)限管理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-11-11
React Hook用法示例詳解(6個(gè)常見(jiàn)hook)
這篇文章主要介紹了React Hook用法詳解(6個(gè)常見(jiàn)hook),本文通過(guò)實(shí)例代碼給大家介紹了6個(gè)常見(jiàn)hook,需要的朋友可以參考下2021-04-04
react18?hooks自定義移動(dòng)端Popup彈窗組件RcPop
這篇文章主要介紹了react18?hooks自定義移動(dòng)端Popup彈窗組件RcPop,react-popup?基于react18+hook自定義多功能彈框組件,整合了msg/alert/dialog/toast及android/ios彈窗效果,需要的朋友可以參考下2023-08-08
React onClick/onChange傳參(bind綁定)問(wèn)題
這篇文章主要介紹了React onClick/onChange傳參(bind綁定)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
React?Refs?的使用forwardRef?源碼示例解析
這篇文章主要為大家介紹了React?之?Refs?的使用和?forwardRef?的源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
React + Node.js實(shí)現(xiàn)圖片上傳功能
最近筆者在開發(fā)個(gè)人博客的后臺(tái)管理系統(tǒng),里面用到了圖片上傳相關(guān)的功能,在這里記錄并分享一下,希望可以幫到大家,話不多說(shuō)直接開始吧,感興趣的朋友可以參考下2024-01-01
react拖拽react-beautiful-dnd一維數(shù)組二維數(shù)組拖拽功能
二維數(shù)組可以拖拽,但是不可以編輯+拖拽,如果想要實(shí)現(xiàn)編輯+拖拽,還是需要轉(zhuǎn)換成一維數(shù)組,本文給大家介紹react拖拽react-beautiful-dnd的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2024-03-03

