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

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

10年的木垒哈萨克网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都全网营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整木垒哈萨克建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联公司从事“木垒哈萨克网站设计”,“木垒哈萨克网站推广”以来,每个客户项目都认真落实执行。

兄弟(无嵌套)组件通信

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

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

组件二

        {this.state.msg}         
event传值
      
    )   } }   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 (
      
        

组件二

        {this.state.msg}         
event传值
      
    )   } }   export default Grandson

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

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

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

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

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


网页题目:React如何实现无嵌套组件通信
文章来源:http://scyanting.com/article/jpdhjp.html

其他资讯