参考网站:www.npmjs.com/package/mob…
安装依赖包
npm install mobx-event-bus2 --save 或者 yarn add mobx-event-bus2
使用情景:
子组件 --CalcPeriodPanel.tsx
- 引入依赖包
import { eventBus, subscribe } from "mobx-event-bus2";
- 构造函数里注册eventbus
eventBus.register(this); - 在逻辑代码方法里面传值
eventbus.post('方法名',值)
- 订阅传过来的值 @subscribe("传值过来的事件名“)
@subscribe("传值过来的事件名“)
事件
// loadingComplete作为事件订阅者处理所有的LoadingComplete事件
@subscribe("LoadingComplete")
loadingComplate(evt: any) {
console.log("CalcPeriodPanel -> reCalcComplete -> evt", evt);
this.setState({ loading: false });
}
子组件 --CalcPeriodPanel.tsx
// 引入
import {enventBus,subscribe } from "mobx-event-bus2";
import { CalcService } from "../../services/CaclService"
export class CalcPeriodPanel extends Component<any,any> {
formRef:any = React.creatRef();
dataForm = "YYYY-MM-DD";
calc_service = new CaclService();
constructor(props:any) {
super(props);
// 注册
eventBus.register(this)
let btc = {
"11.33":"年内最低",
"1999.44":"历史最高"
}
...... // 其他代码
this.state = {
....
}
}
onSubmitClick = (e:any) => {
e.preventDefault();
this.setState({loading:true})
eventBus.post('ReCalc",this.state)
eventBus.post("changeCalcParams",this.state);
eventBus.post("changePrice",this.state);
}
}
父组件 --CalcTable.tsx
- 引入依赖包
import { eventBus, subscribe } from "mobx-event-bus2";
- 构造函数里注册eventbus
eventBus.register(this); - 在逻辑代码方法里面传值
eventbus.post('方法名',值)
- 订阅传过来的值 当方法添加了@subscribe注解的时候,就可以接收发送者发出的消息了
@subscribe("传值过来的事件名“)**当方法添加了该注解的时候,就可以接收发送者发出的消息了** 事件\
import { eventBus, subscribe } from "mobx-event-bus2";
requsetCal(payload:any) {
this.setState({loading:true})
this.calcService.getData(payload).then((response) => {
let data = response.data;
for(let item of data){
....
// 其他代码
}
this.setState((state:any, props:any) => {
.... // 改变状态
},this.HasFavor)
eventBus.post("LoadingComplete",{ loading :false })
}
)
}
@subscribe("ReCalc")
reCacl(event:any){
this.requestcalc(event.payload);
}
@subscirbe("changePrice")
changePrice(event:any) {
this.setState({
isPrice:!this.state.isPrice,
isData:true,
isMode:true,
tableArea: this.state.isShow,
isFollow: false,
}
以上是个人理解,应该有不对的地方,欢迎指正