在不使用redux的情况下 react无关系组件之间如何通信!
来源:互联网 发布:java边界布局 编辑:程序博客网 时间:2024/06/05 07:19
React通信!
对于react,很多时候并不需要redux,但是项目却也非常庞大,这个时候,生命周期函数和context无法满足要求,组件之间的通信太过麻烦,这个时候只能通过其他方法来优化通信!
这里我选择的使用node.js中EventEmitter;
安装EventEmitter
npm install events –save
以下是我的代码:
首先先引入模块
import React from 'react';import ReactDOM from 'react-dom';import { EventEmitter } from 'events';const event = new EventEmitter();
第一个组件
class Send extends React.Component{ constructor(props){ super(props); this.state={ content:'', word:'我是emit' } } sendMsg(){ this.setState({ word:'我能接收数据' }) event.emit('sendMsg','单击发送',data=>{ this.setState({ word:'我能接收数据', content:data }) }); } render(){ const {content,word} = this.state; return ( <div> <button style={button} onClick={this.sendMsg.bind(this)}>{content?content:word}</button> </div> ) }}
第二个组件
class Receive extends React.Component{ constructor(props){ super(props); this.state={ data:'' } } componentDidMount(){ event.on('sendMsg',(msg,data)=>{ this.setState({ data:msg, func:data, }) }) } fnClick(){ this.state.func&&this.state.func('收到!'); } render(){ const {data} = this.state; return ( <div> <button style={button} onClick={this.fnClick.bind(this)}> {data?data:'我是接收'} </button> </div> ) }}
父组件
class Parent extends React.Component{ render(){ return ( <div> 解决无关系组件直接的通信问题! <Send /> <Receive /> </div> ) }}
最后把代码拷贝过去,然后跑起来看看就知道了。这是两个按钮之间的互相通信!
最后附上一张从网上找的react生命周期函数的结构图!解释的很详细!具体是哪个网站就不记得了,以后看见我加引用链接!
阅读全文
1 0
- 在不使用redux的情况下 react无关系组件之间如何通信!
- react-redux,redux,react native之间的关系
- 使用原生redux模块在React组件之间实现数据共享小实例
- React 组件基本使用(三) ---父子组件之间的通信
- React组件之间的通信
- react组件之间的通信
- react组件之间的通信
- React组件之间的通信
- 如何在不装ORACLE的情况下使用PLSQL
- 关于react组件之间的通信
- 在不连接网线的情况下Windos与VM之间如何ping通
- 如何在无光驱情况下,使用BootCamp进行分区
- 利用react-redux实现react组件数据之间数据共享
- (十)Redux:官方react-redux的初步使用(Provider组件、connect函数)
- React 各种组件关系通信
- React 各种组件关系通信
- React 各种组件关系通信
- react-redux的简单使用
- mybatis 中 出现 < > 号情况
- 多重剪贴板【Python】
- [LeetCode] 551. Student Attendance Record I
- 利用计时器实现扫描数码管
- PHP将多维不规则数组转化为数组
- 在不使用redux的情况下 react无关系组件之间如何通信!
- JavaScript == 与 === 区别
- 斗地主算法之叫地主/抢地主简单判定算法
- JavaWeb笔记
- Python3 高级特性
- Java三目运算符和逗号运算符
- 第四弹——CGI&FastCGI
- Jfinal学习(一)
- 属性没有多态