温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React如何实现无嵌套组件通信

发布时间:2022-03-28 11:15:00 来源:亿速云 阅读:259 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关React如何实现无嵌套组件通信,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

兄弟(无嵌套)组件通信

当两个组件互不嵌套,处在同个层级或者不同层级上,他们之间要进行通信,有以下几种常用方法

1、某个组件先将值传到同一个父组件,然后在通过父组件传给另外一个组件,用到父子组件传值

2、使用缓存sessionStorage、localStorage等

3、如果两个组件之间存在跳转,可以使用路由跳转传值,附上详细用法

React学习笔记 -- 组件通信之路由传参(react-router-dom)_前端菜小白leo的博客-CSDN博客

4、event(发布--订阅)

首先,安装event

npm install event -save

新建一个event.js

import { EventEmitter } from 'events'; export default new EventEmitter();

然后另两个组件处于同层级(不同个父组件或者不同层级都可以)

import React from 'react'; import Grandson from './Grandson'; import GrandsonOther from './GrandsonOther';   class Children extends React.Component {   render(){     return (       <div>         <Grandson></Grandson>         <GrandsonOther></GrandsonOther>       </div>     )   } }   export default Children

组件一,导入event,在componentDidMount阶段添加监听addListener(订阅),在componentWillUnmount移除监听removeListener,事件名称与组件二中emit一致。

import React from 'react'; import event from '../event'; import { Button } from 'element-react'   class Grandson extends React.Component {   constructor(props) {	super(props);     this.state = {       msg:''     }     this.toOther = this.toOther.bind(this)   }   toOther(){     event.emit('eventMsg','通过evnet传过来的值')   }   render(){     return (       <div style={{backgroundColor:'#13ce66',padding:'10px',width:'200px',margin:'auto',marginTop:'20px'}}>         <p>组件二</p>         <span style={{color:'blue'}}>{this.state.msg}</span>         <div><Button onClick={this.toOther}>event传值</Button></div>       </div>     )   } }   export default Grandson

组件二,导入event,按钮绑定方法,使用event.emit触发(发布)事件。

import React from 'react'; import event from '../event'; import { Button } from 'element-react'   class Grandson extends React.Component {   constructor(props) {	super(props);     this.state = {       msg:''     }     this.toOther = this.toOther.bind(this)   }   toOther(){     event.emit('eventMsg','通过evnet传过来的值')   }   render(){     return (       <div style={{backgroundColor:'#13ce66',padding:'10px',width:'200px',margin:'auto',marginTop:'20px'}}>         <p>组件二</p>         <span style={{color:'blue'}}>{this.state.msg}</span>         <div><Button onClick={this.toOther}>event传值</Button></div>       </div>     )   } }   export default Grandson

点击按钮,组件二发布事件,组件一监听(订阅)事件,更新内容。(如果交换发布者订阅者身份,写法一致)

React如何实现无嵌套组件通信

React如何实现无嵌套组件通信

注意:如果两个组件使用event进行通信,确保发布订阅的事件名称一致,如上例中 eventMsg

关于“React如何实现无嵌套组件通信”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI