在使用 React 的過程中,不可避免的需要組件間進行消息傳遞(通信),組件間通信大體有下面幾種情況:
- 父組件向子組件通信
- 子組件向父組件通信
- 跨級組件之間通信
- 非嵌套組件間通信
下面依次說下這幾種通信方式。
父組件向子組件通信
這是最簡單也是最常用的一種通信方式:父組件通過向子組件傳遞 props,子組件得到 props 後進行相應的處理。
下面是演示代碼:
父組件 App.js:
import React,{ Component } from "react";
import Sub from "./SubComponent.js";
import "./App.css";
export default class App extends Component{
render(){
return(
<div>
<Sub title = "今年過節不收禮" />
</div>
)
}
}
子組件 SubComponent.js:
import React from "react";
const Sub = (props) => {
return(
<h1>
{ props.title }
</h1>
)
}
export default Sub;
子組件向父組件通信
利用回調函數,可以實現子組件向父組件通信:父組件將一個函數作爲 props 傳遞給子組件,子組件調用該回調函數,便可以向父組件通信。
下面是演示代碼:
SubComponent.js:
import React from "react";
const Sub = (props) => {
const cb = (msg) => {
return () => {
props.callback(msg)
}
}
return(
<div>
<button onClick = { cb("我們通信把") }>點擊我</button>
</div>
)
}
export default Sub;
App.js:
import React,{ Component } from "react";
import Sub from "./SubComponent.js";
import "./App.css";
export default class App extends Component{
callback(msg){
console.log(msg);
}
render(){
return(
<div>
<Sub callback = { this.callback.bind(this) } />
</div>
)
}
}
跨級組件通信
所謂跨級組件通信,就是父組件向子組件的子組件通信,向更深層的子組件通信。跨級組件通信可以採用下面兩種方式:
- 中間組件層層傳遞 props
- 使用 context 對象
對於第一種方式,如果父組件結構較深,那麼中間的每一層組件都要去傳遞 props,增加了複雜度,並且這些 props 並不是這些中間組件自己所需要的。不過這種方式也是可行的,當組件層次在三層以內可以採用這種方式,當組件嵌套過深時,採用這種方式就需要斟酌了。
使用 context 是另一種可行的方式,context 相當於一個全局變量,是一個大容器,我們可以把要通信的內容放在這個容器中,這樣一來,不管嵌套有多深,都可以隨意取用。
使用 context 也很簡單,需要滿足兩個條件:
- 上級組件要聲明自己支持 context,並提供一個函數來返回相應的 context 對象
- 子組件要聲明自己需要使用 context
下面以代碼說明,我們新建 3 個文件:父組件 App.js,子組件 Sub.js,子組件的子組件 SubSub.js。
App.js:
import React, { Component } from 'react';
import PropTypes from "prop-types";
import Sub from "./Sub";
import "./App.css";
export default class App extends Component{
// 父組件聲明自己支持 context
static childContextTypes = {
color:PropTypes.string,
callback:PropTypes.func,
}
// 父組件提供一個函數,用來返回相應的 context 對象
getChildContext(){
return{
color:"red",
callback:this.callback.bind(this)
}
}
callback(msg){
console.log(msg)
}
render(){
return(
<div>
<Sub></Sub>
</div>
);
}
}
Sub.js:
import React from "react";
import SubSub from "./SubSub";
const Sub = (props) =>{
return(
<div>
<SubSub />
</div>
);
}
export default Sub;
SubSub.js:
import React,{ Component } from "react";
import PropTypes from "prop-types";
export default class SubSub extends Component{
// 子組件聲明自己需要使用 context
static contextTypes = {
color:PropTypes.string,
callback:PropTypes.func,
}
render(){
const style = { color:this.context.color }
const cb = (msg) => {
return () => {
this.context.callback(msg);
}
}
return(
<div style = { style }>
SUBSUB
<button onClick = { cb("我胡漢三又回來了!") }>點擊我</button>
</div>
);
}
}
如果是父組件向子組件單向通信,可以使用變量,如果子組件想向父組件通信,同樣可以由父組件提供一個回調函數,供子組件調用,回傳參數。
在使用 context 時,有兩點需要注意:
- 父組件需要聲明自己支持 context,並提供 context 中屬性的 PropTypes
- 子組件需要聲明自己需要使用 context,並提供其需要使用的 context 屬性的 PropTypes
- 父組件需提供一個 getChildContext 函數,以返回一個初始的 context 對象
如果組件中使用構造函數(constructor),還需要在構造函數中傳入第二個參數 context,並在 super 調用父類構造函數是傳入 context,否則會造成組件中無法使用 context。
...
constructor(props,context){
super(props,context);
}
...
改變 context 對象
我們不應該也不能直接改變 context 對象中的屬性,要想改變 context 對象,只有讓其和父組件的 state 或者 props 進行關聯,在父組件的 state 或 props 變化時,會自動調用 getChildContext 方法,返回新的 context 對象,而後子組件進行相應的渲染。
修改 App.js,讓 context 對象可變:
import React, { Component } from 'react';
import PropTypes from "prop-types";
import Sub from "./Sub";
import "./App.css";
export default class App extends Component{
constructor(props) {
super(props);
this.state = {
color:"red"
};
}
// 父組件聲明自己支持 context
static childContextTypes = {
color:PropTypes.string,
callback:PropTypes.func,
}
// 父組件提供一個函數,用來返回相應的 context 對象
getChildContext(){
return{
color:this.state.color,
callback:this.callback.bind(this)
}
}
// 在此回調中修改父組件的 state
callback(color){
this.setState({
color,
})
}
render(){
return(
<div>
<Sub></Sub>
</div>
);
}
}
此時,在子組件的 cb 方法中,傳入相應的顏色參數,就可以改變 context 對象了,進而影響到子組件:
...
return(
<div style = { style }>
SUBSUB
<button onClick = { cb("blue") }>點擊我</button>
</div>
);
...
context 同樣可以應在無狀態組件上,只需將 context 作爲第二個參數傳入:
import React,{ Component } from "react";
import PropTypes from "prop-types";
const SubSub = (props,context) => {
const style = { color:context.color }
const cb = (msg) => {
return () => {
context.callback(msg);
}
}
return(
<div style = { style }>
SUBSUB
<button onClick = { cb("我胡漢三又回來了!") }>點擊我</button>
</div>
);
}
SubSub.contextTypes = {
color:PropTypes.string,
callback:PropTypes.func,
}
export default SubSub;
非嵌套組件間通信
非嵌套組件,就是沒有任何包含關係的組件,包括兄弟組件以及不在同一個父級中的非兄弟組件。對於非嵌套組件,可以採用下面兩種方式:
- 利用二者共同父組件的 context 對象進行通信
- 使用自定義事件的方式
如果採用組件間共同的父級來進行中轉,會增加子組件和父組件之間的耦合度,如果組件層次較深的話,找到二者公共的父組件不是一件容易的事,當然還是那句話,也不是不可以...
這裏我們採用自定義事件的方式來實現非嵌套組件間的通信。
我們需要使用一個 events 包:
npm install events --save
新建一個 ev.js,引入 events 包,並向外提供一個事件對象,供通信時使用:
import { EventEmitter } from "events";
export default new EventEmitter();
App.js:
import React, { Component } from 'react';
import Foo from "./Foo";
import Boo from "./Boo";
import "./App.css";
export default class App extends Component{
render(){
return(
<div>
<Foo />
<Boo />
</div>
);
}
}
Foo.js:
import React,{ Component } from "react";
import emitter from "./ev"
export default class Foo extends Component{
constructor(props) {
super(props);
this.state = {
msg:null,
};
}
componentDidMount(){
// 聲明一個自定義事件
// 在組件裝載完成以後
this.eventEmitter = emitter.addListener("callMe",(msg)=>{
this.setState({
msg
})
});
}
// 組件銷燬前移除事件監聽
componentWillUnmount(){
emitter.removeListener(this.eventEmitter);
}
render(){
return(
<div>
{ this.state.msg }
我是非嵌套 1 號
</div>
);
}
}
Boo.js:
import React,{ Component } from "react";
import emitter from "./ev"
export default class Boo extends Component{
render(){
const cb = (msg) => {
return () => {
// 觸發自定義事件
emitter.emit("callMe","Hello")
}
}
return(
<div>
我是非嵌套 2 號
<button onClick = { cb("blue") }>點擊我</button>
</div>
);
}
}
自定義事件是典型的發佈/訂閱模式,通過向事件對象上添加監聽器和觸發事件來實現組件間通信。
總結
本文總結了 React 中組件的幾種通信方式,分別是:
- 父組件向子組件通信:使用 props
- 子組件向父組件通信:使用 props 回調
- 跨級組件間通信:使用 context 對象
- 非嵌套組件間通信:使用事件訂閱
事實上,在組件間進行通信時,這些通信方式都可以使用,區別只在於使用相應的通信方式的複雜程度和個人喜好,選擇最合適的那一個。比如,通過事件訂閱模式通信不止可以應用在非嵌套組件間,還可以用於跨級組件間,非嵌套組件間通信也可以使用 context 等。關鍵是選擇最合適的方式。
當然,自己實現組件間的通信還是太難以管理了,因此出現了很多狀態管理工具,如 flux、redux 等,使用這些工具使得組件間的通信更容易追蹤和管理。
完。
作者:Charleylla
鏈接:https://www.jianshu.com/p/fb915d9c99c4
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯繫作者獲得授權並註明出處。