React 组件间通信介绍
React 组件间通信方式简介
React 组件间通信主要分为以下四种情况:
- 父组件向子组件通信
- 子组件向父组件通信
- 跨级组件之间通信
- 非嵌套组件间通信
下面对这四种情况分别进行介绍:
父组件向子组件通信
父组件通过 props 和子组件进行通信,子组件得到 props 后进行相应的操作
父组件 App.js:
import React, { Component } from 'react';import './App.css';import Child1 from './Child1';class App extends Component {render() {return (<div className="App"><Child1 content="父组件传递的内容" /></div>);}}export default App;
子组件 Child1.jsx
import React, { Component } from 'react';class Child1 extends Component {render () {return (<div>子组件一:{ this.props.content }</div>)}}export default Child1;
子组件向父组件通信
和父组件向子组件通信类似,父组件通过传递 props 给子组件,只不过 props 的内容是一个函数,子组件通过调用父组件传递过来的回调函数,将子组件内容传递给父组件。
父组件 App.js
import React, { Component } from 'react';import logo from './logo.svg';import './App.css';import Child1 from './Child1';import Child2 from './Child2';class App extends Component {constructor(){super();this.state = {msg:'',}}childMsg(msg){this.setState({msg: msg,})}render() {return (<div className="App">子组件二传过来的内容:{this.state.msg}<Child2 childMsg={this.childMsg.bind(this)}/></div>);}}export default App;
子组件 Child2.jsx:
import React, { Component } from 'react';class Child2 extends Component {msgHandle(){this.props.childMsg(this.refs.input.value);}render () {return (<div>子组件二:<input type="text" placeholder='请输入内容' ref='input' /><button onClick={this.msgHandle.bind(this)}>点击向父组件传参</button></div>)}}export default Child2;
跨级组件通信
跨级组件是指父组件向子组件的子组件进行通信,或者向更深层次的子组件通信,主要有两种方式:
- 通过 props 层层传递
- 使用 context 对象
对于层级不深的组件(三层以内),可以使用 props 进行层层传递,如果说层级更深的话,
每一层组件都要去传递 props,并且这些 props 可能不是自身需要的,这就增加了复杂度,这种场景就可以使用 context 进行通信。context 是一个全局变量,相当于一个大容器,我们把要传递的信息放到这个容器里面,不管嵌套层级多深,子组件都可以获取到信息。使用 context 需要满足以下三个条件:
1、父组件需要声明自己支持 context,并提供 context 对象中属性的 PropTypes
2、子组件需要声明自己需要使用 context,并提供其需要使用的 context 属性的 PropTypes。
3、父组件需要提供一个 getChildContext 函数,用来返回一个初始的 context 对象
props 层层传递:
父组件App.js:
import React, { Component } from 'react';import logo from './logo.svg';import './App.css';import Child1 from './Child1';class App extends Component {constructor(){super();}render() {return (<div className="App"><Child1 content="父组件传递给孙子组件的内容" /></div>);}}export default App;
Child1.jsx:
import React, { Component } from 'react';import Child1_1 from './Child1_1';class Child1 extends Component {render () {return (<div><Child1_1 content={this.props.content}/></div>)}}export default Child1;
Child1_1.jsx:
import React, { Component } from 'react';class Child1_1 extends Component {render () {return (<div>子组件一的子组件:{ this.props.content }</div>)}}export default Child1_1;
context 对象传递
父组件App.js:
import React, { Component } from 'react';import logo from './logo.svg';import './App.css';import PropTypes from "prop-types";import Child1 from './Child1';class App extends Component {// 声明支持 contextstatic childContextTypes = {msgs: PropTypes.string,callBack: PropTypes.func,}// 父组件提供一个函数,返回初始的 context 对象getChildContext(){return {msgs:'父组件传递的初始内容',callBack:this.callBack}}callBack(msgs){console.log(msgs);}render() {return (<div className="App"><Child1 /></div>);}}export default App;
子组件 Child1.jsx:
import React, { Component } from 'react';import Child12 from './Child1_2';class Child1 extends Component {render () {return (<div><Child12 /></div>)}}export default Child1;
子组件的子组件 Child1_2:
import React, { Component } from 'react';import PropTypes from 'prop-types';class Child1_2 extends Component {// 子组件声明需要调动 contextstatic contextTypes = {msgs:PropTypes.string,callBack:PropTypes.func}callBack(){this.context.callBack('孙子组件的信息');}render () {return (<div>子组件一的子组件:{ this.context.msgs }<button onClick={this.callBack.bind(this)}>点击给爷爷组件传递信息</button></div>)}}export default Child1_2;
非嵌套组件间通信
表示没有任何包含关系的组件,主要包括兄弟组件和不在同一个父级中的非兄弟组件。
- 使用共同父组件的 context 对象通信
- 使用自定义事件的方式
对于使用共同父组件 context 的方式会增加子组件和父组件之间的耦合度,对于层级较深的组件找到共同父组件也比较麻烦,但是这种方式可实施。
为了避免父子组件之间的耦合度,我们采用自定义事件的方式:
需要安装 events 包,使用该模块的自定义事件机制npm i events --save
在根目录下新建 events.js 文件:
import { EventEmitter } from 'events';export default new EventEmitter();
父组件 App.js:
import React, { Component } from 'react';import logo from './logo.svg';import './App.css';import Child1 from './Child1';import Child2 from './Child2';class App extends Component {render() {return (<div className="App"><Child1 /><Child2 /></div>);}}export default App;
子组件 Child1.jsx:
import React, { Component } from 'react';import emitter from './events';class Child1 extends Component {constructor(props){super(props);this.state = {msg:''}}// 组件挂载完后,声明一个自定义事件componentDidMount(){this.eventEmitter = emitter.addListener('selfEventName',msg => {this.setState({msg: msg})})}// 组件销毁前清除事件监听componentWillUnmount(){emitter.removeListener(this.eventEmitter)}render () {return (<div>子组件二传递过来的内容:{ this.state.msg }</div>)}}export default Child1;
子组件 Child2.jsx:
import React, { Component } from 'react';import emitter from './events';class Child2 extends Component {msgHandle(){emitter.emit('selfEventName','自定义事件传参');}render () {return (<div>子组件二:<button onClick={this.msgHandle.bind(this)}>点击向父组件传参</button></div>)}}export default Child2;
React 组件间通信介绍的更多相关文章
- vue 和 react 组件间通信方法对比
vue 和 react 组件间通信方法对比: 通信路径 vue的方法 react的方法 父组件 => 子组件 props(推荐).slot(推荐).this.$refs.this.$childr ...
- React组件间通信-sub/pub机制
React生命周期第二个demo演示了兄弟组件的通信,需要通过父组件,比较麻烦:下面介绍sub/pub机制来事项组件间通信. 1.导包 npm i pubsub-js 2.UserSearch.jsx ...
- React 组件间通信 总结
组件间通信 5.1.1. 方式一: 通过props传递 1) 共同的数据放在父组件上, 特有的数据放在自己组件内部(state) 2) 通过props可以传递一般数据和 ...
- React组件间通信
众所周知,ReactJS组件与组件之间的通信是一个难点.在React实际开发中,父子组件之间的传值是比较常见的,刚入门的小伙伴很容易被组件之间的通信绕懵. 今天花了点时间总结了一下React父子组件之 ...
- react 组件间通信,父子间通信
一.父组件传值给子组件 父组件向下传值是使用了props属性,在父组件定义的子组件上定义传给子组件的名字和值,然后在子组件通过this.props.xxx调用就可以了. 二.子组件传值给父组件 子组件 ...
- React 组件间通信
https://jsfiddle.net/69z2wepo/9719/ <script src="https://facebook.github.io/react/js/jsfiddl ...
- React独立组件间通信联动
React是现在主流的高效的前端框架,其官方文档 http://reactjs.cn/react/docs/getting-started.html 在介绍组件间通信时只给出了父子组件间通信的方法,而 ...
- React 精要面试题讲解(二) 组件间通信详解
单向数据流与组件间通信 上文我们已经讲述过,react 单向数据流的原理和简单模拟实现.结合上文中的代码,我们来进行这节面试题的讲解: react中的组件间通信. 那么,首先我们把看上文中的原生js代 ...
- [转] React 中组件间通信的几种方式
在使用 React 的过程中,不可避免的需要组件间进行消息传递(通信),组件间通信大体有下面几种情况: 父组件向子组件通信 子组件向父组件通信 跨级组件之间通信 非嵌套组件间通信 下面依次说下这几种通 ...
随机推荐
- 搭建SSH框架心得
<Struts2+Spring4+hibernate3> 工程结构 导入相关jar包:自行网上百度即可,根据环境需要 写dao类 以及实现 package com.icommon.dao; ...
- kubernetes二进制部署k8s-master集群controller-manager服务unhealthy问题
一.问题现象 我们使用二进制部署k8s的高可用集群时,在部署多master时,kube-controller-manager服务提示Unhealthy [root@ceph-01 system]# k ...
- css设置垂直居中方式总结
方式1:flex布局,display:flex;align-items:center <!DOCTYPE html> <html lang="en"> &l ...
- shell 统计字符串 字符个数
统计“abbc”中“b”的个数 1:awknum=`echo abbc | awk -F"b" '{print NF-1}'` 2:trnum=`echo abbc | tr -c ...
- Web服务器软件 (Tomcat)
1.什么是服务器? 安装了服务器的软件的计算机 服务器软件:接收用户的请求(request),处理请求,做出响应. Web服务器软件:接收用户的请求(request),处理请求,做出响应,再Web服务 ...
- 禁用ViewPager的滑动事件
public class NoScrollViewPager extends ViewPager { private boolean noScroll = false; public NoScroll ...
- Spring在项目中需要的配置
要想了解Spring,首先要了解三层架构.....自行百度. 1.Spring相关概念: 少数jar+某一个功能的配置文件 Spring容器(轻量级):帮我们管理业务逻辑层,有很多业务逻辑对象,需要对 ...
- GDB程序调试
GDB使用流程 1.编译生成可执行文件: gcc -g tst.c -o tst2.启动GDB gdb tst3. 在main 函数处设置断点 break main4. 运行程序 run GDB 命令 ...
- c# 在.NET使用Newtonsoft.Json转换,读取,写入json
转自:http://blog.sina.com.cn/s/blog_70686f3a0101kemg.html 首先,大家要明白什么是json,了解更多关于json方面资料大家可以点击https:/ ...
- Linux常用命令练习
实验结论 熟悉命令倒不是什么难的过程,很容易就能跟着指示打出来并明白其效果与作用.难就难在了感受不到这些命令的实际意义,即如何有效的结合起来并在项目中运用,这就导致了很大的迷茫与无力感. cat fi ...