https://segmentfault.com/a/1190000012361461

需要组件之进行通信的几种情况

  • 父组件向子组件通信
  • 子组件向父组件通信
  • 跨级组件通信
  • 没有嵌套关系组件之间的通信

1. 父组件向子组件通信

React数据流动是单向的,父组件向子组件通信也是最常见的;父组件通过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. 子组件向父组件通信

  • 利用回调函数
  • 利用自定义事件机制

回调函数

实现在子组件中点击隐藏组件按钮可以将自身隐藏的功能

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

观察一下实现方法,可以发现它与传统回调函数的实现方法一样.而且setState一般与回调函数均会成对出现,因为回调函数即是转换内部状态是的函数传统;

3. 跨级组件通信

  • 层层组件传递props

例如A组件和B组件之间要进行通信,先找到A和B公共的父组件,A先向C组件通信,C组件通过props和B组件通信,此时C组件起的就是中间件的作用

  • 使用context

context是一个全局变量,像是一个大容器,在任何地方都可以访问到,我们可以把要通信的信息放在context上,然后在其他组件中可以随意取到;
但是React官方不建议使用大量context,尽管他可以减少逐层传递,但是当组件结构复杂的时候,我们并不知道context是从哪里传过来的;而且context是一个全局变量,全局变量正是导致应用走向混乱的罪魁祸首.

使用context

下面例子中的组件关系: 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,
}
// 提供一个函数,用来返回相应的context对象
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. 没有嵌套关系的组件通信

  • 使用自定义事件机制

在componentDidMount事件中,如果组件挂载完成,再订阅事件;在组件卸载的时候,在componentWillUnmount事件中取消事件的订阅;
以常用的发布/订阅模式举例,借用Node.js Events模块的浏览器版实现

使用自定义事件的方式

下面例子中的组件关系: List1和List2没有任何嵌套关系,App是他们的父组件;

实现这样一个功能: 点击List2中的一个按钮,改变List1中的信息显示
首先需要项目中安装events 包:

npm install events --save

在src下新建一个util目录里面建一个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() {
// 组件装载完成以后声明一个自定义事件
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')}>点击我改变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>
);
}
}

自定义事件是典型的发布订阅模式,通过向事件对象上添加监听器和触发事件来实现组件之间的通信

总结

  • 父组件向子组件通信: props
  • 子组件向父组件通信: 回调函数/自定义事件
  • 跨级组件通信: 层层组件传递props/context
  • 没有嵌套关系组件之间的通信: 自定义事件

React中组件通信的几种方式的更多相关文章

  1. react中的ref的3种方式

    2020-03-31 react中的ref的3种方式 react中ref的3种绑定方式 方式1: string类型绑定 类似于vue中的ref绑定方式,可以通过this.refs.绑定的ref的名字获 ...

  2. Vue中组件通信的几种方法(Vue3的7种和Vue2的12种组件通信)

    Vue3组件通信方式: props $emit expose / ref $attrs v-model provide / inject Vuex 使用方法: props 用 props 传数据给子组 ...

  3. vue组件通信的几种方式

    最近用vue开发项目,记录一下vue组件间通信几种方式 第一种,父子组件通信 一.父组件向子组件传值 1.创建子组件,在src/components/文件夹下新建一个Child.vue 2.Child ...

  4. 5.React中组件通信问题

    1.父组件传递值给子组件 想必这种大家都是知道的吧!都想到了用我们react中的props,那么我在这简单的写了小demo,请看父组件 class Parent extends Component{ ...

  5. Vue自定义组件以及组件通信的几种方式

    本帖子来源:小贤笔记 功能 组件 (Component) 是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.在较高层面上,组件是自定义元素,Vue.js 的编译器为它 ...

  6. Angular 组件通信的三种方式

    我们可以通过以下三种方式来实现: 传递一个组件的引用给另一个组件 通过子组件发送EventEmitter和父组件通信 通过serive通信 1. 传递一个组件的引用给另一个组件 Demo1 模板引用变 ...

  7. [转] React 中组件间通信的几种方式

    在使用 React 的过程中,不可避免的需要组件间进行消息传递(通信),组件间通信大体有下面几种情况: 父组件向子组件通信 子组件向父组件通信 跨级组件之间通信 非嵌套组件间通信 下面依次说下这几种通 ...

  8. React中组件间通信的方式

    React中组件间通信的方式 React中组件间通信包括父子组件.兄弟组件.隔代组件.非嵌套组件之间通信. Props props适用于父子组件的通信,props以单向数据流的形式可以很好的完成父子组 ...

  9. React组件导入的两种方式(动态导入组件的实现)

    一. react组件两种导入方式 React组件可以通过两种方式导入另一个组件 import(常用) import component from './component' require const ...

随机推荐

  1. Java笔记_web.xml文件

    在JavaEE工程中,web.xml文件是用来初始化配置信息:比如Welcome页面.servlet.servlet-mapping.filter.listener.启动加载级别等,但并不是必须的,一 ...

  2. .Net Core3.0使用gRPC 和IdentityServer4

    gRPC是什么gRPC是可以在任何环境中运行的现代开源高性能RPC框架.它可以通过可插拔的支持来有效地连接数据中心内和跨数据中心的服务,以实现负载平衡,跟踪,运行状况检查和身份验证.它也适用于分布式计 ...

  3. nginx location指令详解

    Nginx的HTTP配置主要包括三个区块,结构如下: http { //这个是协议级别 include mime.types; default_type application/octet-strea ...

  4. Lombok简介、使用、工作原理、优缺点

    1.Lombok简介官方介绍 Project Lombok is a java library that automatically plugs into your editor and build ...

  5. JAAS configuration for Kafka clients

    Clients may configure JAAS using the client configuration property sasl.jaas.config or using the sta ...

  6. ffmpeg命令参数详解

    ffmpeg命令参数详解 http://linux.51yip.com/search/ffmpeg ffmpeg图片加滤镜效果 参考:https://cloud.tencent.com/develop ...

  7. Zookeeper学习笔记:简单注册中心

    zookeeper可以作为微服务注册中心,spring cloud也提供了zookeeper注册中心的支持. 本文介绍如何实现一个简单的zookeeper注册中心,主要的实现方式: n个服务提供者对外 ...

  8. 一篇文章搞定redis

    Redis 简介 Redis 是完全开源免费的,遵守 BSD 协议,是一个高性能的 key - value 数据库 Redis 与 其他 key - value 缓存产品有以下三个特点: Redis ...

  9. Go的运算符

    1 算术运算符 运算符 术语 示例 结果 + 加 10 + 5 15 - 减 10 - 5 5 * 乘 10 * 5 50 / 除 10 / 5 2 % 取模(取余) 10 % 3 1 ++ 后自增, ...

  10. python基础05--深浅copy, set,bytes

    1.1 深浅 copy 1. =  赋值操作, lis1=[1,2,3]  list2 = list1  list1.append(4)  则list1,list2都变 赋值都指向同一个地址,改变一个 ...