核心代码:
const eventBus = {
evnetList: [],
// 监听事件
pushFun(callbackFun, name) {
// 同名事件 过滤
if (this.evnetList.length > 0 && this.evnetList.find(i => i.name === name)) {
this.evnetList = this.evnetList.filter(i => i.name !== name)
}
this.evnetList = [...this.evnetList, {
name, callbackFun }]
},
//触发事件
dispath(name, data = '') {
if (!name) {
return false;
}
this.evnetList.forEach(element => {
if (name === element.name) {
element.callbackFun(data)
}
});
},
// 取消事件监听
$remove(name = "") {
// console.log(name, "取消事件监听")
this.evnetList = [...this.evnetList.filter(i => i.name !== name)]
}
}
export default eventBus
上面是创建了一个js模块,总的来说是个对象,有三个属性,第一个evnetList是来存储对象的,这个对象通过pushFun来改变evnetList数组,格式如下:
evnetList: [{
name:'zjq',
callbackFun:()=>{
}
}],
最终能通过触发方法dispath来触发对应name的函数,每一个函数的唯一标识就是name;
下面看一下使用:
1.js
componentDidMount() {
eventFun.pushFun((e) => {
console.log('e===我是菜单选项二传递过来的参数', e);
this.setState({
valueTopStr: e
})
}, 'childTopFun')
}
2.js
import React from "react";
import {
Button, Input } from 'element-react';
import eventFun from "../../js/eventFun";
export default class Childtop extends React.Component {
constructor() {
super()
}
state = {
valueStr: ''
}
change() {
console.log('this.state.valueStr===', this.state.valueStr);
eventFun.dispath('childTopFun',this.state.valueStr)
}
changeFun(e) {
console.log('e===', e);
this.setState({
valueStr: e
})
}
render() {
return (
<div>
<p>我是childTop组件</p>
<Input placeholder="请输入内容" value={
this.state.valueStr} onChange={
(e) => {
this.changeFun(e) }} />
<Button type="success" onClick={
() => {
this.change() }}>点击给top组件发送信息</Button>
</div>
)
}
}
1页面挂载的时候就开始监听name为childTopFun的事件函数,在2中,在input中输入点击按钮触发childTopFun事件,完成事件传递~