在不使用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生命周期函数的结构图!解释的很详细!具体是哪个网站就不记得了,以后看见我加引用链接!
钩子函数