Skip to main content

组件通讯

在react使用过程中,不可避免的会使用到组件通讯,常见的几种情况如下:

  • 父组件到子组件: 父组件通过props传递属性到子组件, 然后子组件自行处理。
  • 子组件到父组件: 父组件通过props传递function到子组件
  • 跨级组件: 找到公共的父组件A,然后A通过props传递属性到子组件,不过不建议,组件通信多了那将是魔鬼般的存在,可以使用 context对象
  • 非嵌套组件: 使用事件订阅

下面依次说下上面几种通讯常用的方法:

1、父组件到子组件

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 = "今年过节不收礼" name='scott' age={18}/>
</div>
)
}
}

子组件 SubComponent.js:父组件传递的数据会被react自动封装到props对象中

import React from "react";

const Sub = (props) => {
const { title, name, age } = props
return(
<h1>
{ title } - { name } - { age }
</h1>
)
}

export default Sub;

or

import React from "react";

const Sub = ({title, name, age}) => {
return(
<h1>
{ title } - { name } - { age }
</h1>
)
}

export default Sub;

2、子组件到父组件:利用回调函数。

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);
}

//推荐这种写法:赋值语句+箭头函数
callback2 = () => {
console.log(msg2)
}
render(){
return(
<div>
<Sub callback = { this.callback.bind(this) } callback2={this.callback2}/>
</div>
)
}
}

子组件:SubComponent.js

import React from "react";

const Sub = (props) => {
const cb = (msg) => {
return () => {
props.callback(msg)
}
}
return(
<div>
<button onClick = { cb("我们通信把") }>btn1</button>
<button onClick = { cb("我们通信把") }>btn2</button>
</div>
)
}

export default Sub;

3、跨级组件:所谓跨级组件通信,就是父组件向子组件的子组件通信,向更深层的子组件通信。跨级组件通信可以采用下面两种方式:

  • 中间组件层层传递 props
  • 使用 context 对象

对于第一种方式,如果父组件结构较深,那么中间的每一层组件都要去传递 props,增加了复杂度,并且这些 props 并不是这些中间组件自己所需要的。不过这种方式也是可行的,当组件层次在三层以内可以采用这种方式,当组件嵌套过深时,采用这种方式就需要斟酌了。

使用 context 是另一种可行的方式,context 相当于一个全局变量,是一个大容器,我们可以把要通信的内容放在这个容器中,这样一来,不管嵌套有多深,都可以随意取用。

使用 context 也很简单,需要满足两个条件:

  • 上级组件要声明自己支持 context,并提供一个函数来返回相应的 context 对象
  • 子组件要声明自己需要使用 context

父组件 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。

如果要改变context对象,需要将其与父组件的state或者props相关联,通过改变该父组件的state或者props来改变context。在父组件的 state 或 props 变化时,会自动调用 getChildContext 方法,返回新的 context 对象,而后子组件进行相应的渲染。

4、非嵌套组件:就是没有任何包含关系的组件,包括兄弟组件以及不在同一个父级中的非兄弟组件。对于非嵌套组件,可以采用下面两种方式:

  • 利用二者共同父组件的 context 对象进行通信
  • 使用自定义事件的方式

如果采用组件间共同的父级来进行中转,会增加子组件和父组件之间的耦合度,如果组件层次较深的话,找到二者公共的父组件不是一件容易的事。

这里我们采用自定义事件的方式来实现非嵌套组件间的通信。

我们需要使用一个 events 包:

npm install events --save

在src下新建一个utils文件夹,新增文件events.js:

向外提供一个事件对象:

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 等,使用这些工具使得组件间的通信更容易追踪和管理。