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 的过程中,不可避免的需要组件间进行消息传递(通信),组件间通信大体有下面几种情况: 父组件向子组件通信 子组件向父组件通信 跨级组件之间通信 非嵌套组件间通信 下面依次说下这几种通 ...
随机推荐
- R语言求根
求根是数值计算的一个基本问题,一般采用的都是迭代算法求解,主要有不动点迭代法.牛顿-拉富生算法.割线法和二分法. 不动点迭代法 所谓的不动点是指x=f(x)的那些点,而所谓的不懂点迭代法是指将原方程化 ...
- egret贝塞尔曲线运动
class MtwGame { public constructor() { } private static _instance: MtwGame; public static get Instan ...
- IIS7.5修改asp的文件上传限制方法
第一.IIS7.5修改asp的文件上传限制方法 1.打开IIS 2.打开面板中的应用程序开发 asp 3.找到最后的限制属性 4.修改其中的最大请求实体主体限制的值:默认为200000字节,等于195 ...
- Redis基础入门
学习redis之前,要了解NoSQL.. 一.NoSql概述 由于关系型数据库很难实现: 1.高并发读写 2.海量数据的高校率存储和访问 3.高可扩展性和高可用性 所以出现NoSql,(Not Onl ...
- WordCount优化版测试小程序实现
Github地址:https://github.com/hcy6668/wordCountPro.git PSP表格: PSP PSP阶段 预估耗时(小时) 实际耗时(小时) Planning ...
- JavaWeb笔记三、MVC 设计模式
一.通过 MVC 进行查询和删除操作 1. 准备一个数据表(examstudent) 2. 创建一个 查询 页面(test.jsp) 通过连接进入 Servlet(listAllStudents.ja ...
- admin 自定义字段颜色 并加以简单判断
在model中class Books(models.Model): nid = models.AutoField(primary_key=True, ) title = models.CharFiel ...
- The Preliminary Contest for ICPC China Nanchang National Invitational I题
Alice has a magic array. She suggests that the value of a interval is equal to the sum of the values ...
- selenium中切换浏览器不同tab 的操作
from selenium import webdriverimport timedriver=webdriver.Chrome()driver.get('http://ui.imdsx.cn/uit ...
- 第一次靶场练习:SQL注入(1)
SQL注入1 本文章目的是对相关的黑客内容进一步了解,如有人违反相关的法律法规,本人概不负责 一.学习目的: 利用手工注入网站 利用sqlmab注入 二.附件说明 靶场网址:http://117.41 ...