一、什么是事件总线?
EventBus 又称为事件总线。在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件,但也就是太方便所以若使用不慎,就会造成难以维护的灾难,因此才需要更完善的Vuex作为状态管理中心,将通知的概念上升到共享状态层次。
但在React中没有EventBus的概念,可以通过 node events模块进行模拟
二、举例:通过Bigson组件中的一个按钮,来改变Smallson组件中的age,由16变为18
1、这是react模拟的事件总线
import React from 'react'
import Bigson from './Bigson'//引入Bigson组件
import Smallson from './Smallson'//引入Smallson组件
class Bus extends React.Component{
render(){
return (
<div>
<p>这是react模拟的事件总线</p>
<hr/>
<Bigson></Bigson>
<hr/>
<Smallson></Smallson>
</div>
)
}
}
export default Bus
2、(关键点)这里是作为中间桥梁的bus组件,用来注册事件和触发事件
import {EventEmitter} from 'events' //引入events事件
const bus={...EventEmitter.prototype} //将events事件原型链,拓展到bus上
export default bus //往bus上注册事件,通过bus触发事件
3、这是Smallson组件
import React from 'react'
import bus from '../../../module/bus' //引入中间量bus,注册事件,被控组件
class Smallson extends React.Component{
constructor(props){
super(props)
this.state={
age:16
}
}
//在挂载之前注册事件,bus绑定add事件
componentWillMount(){
bus.on('add',()=>{
this.setState({age:18})
})
}
render(){
return (
<div>
<p>这是Smallson组件</p>
<p>age:{this.state.age}</p>
</div>
)
}
}
export default Smallson
4、这是Bigson组件
import React from 'react'
import bus from '../../../module/bus' //引入中间量bus,触发事件,主控组件
class Bigson extends React.Component{
chageSmallson(){
bus.emit('add') //触发bus绑定的add事件
}
render(){
return (
<div>
<p>这是Bigson组件</p>
<button onClick={this.chageSmallson}>改变Smallson的age</button>
</div>
)
}
}
export default Bigson
感谢浏览!文章是个人学习笔记,若有不恰当之处,欢迎留言。
转载,请注明出处:https://blog.youkuaiyun.com/qq_41287423
谢谢!٩(๑❛ᴗ❛๑)۶