其他分享
首页 > 其他分享> > 信息传递 订阅(subscribe)-发布(publish) --- react

信息传递 订阅(subscribe)-发布(publish) --- react

作者:互联网

兄弟组件间通信不必再像使用props那种通过父组件来通信,多层组件之间通信也不必在一层一层的传递, 直接在触发事件的组件中发布消息 监听组件中订阅消息即可;

下载:工具库: PubSubJS

指令: npm install pubsub-js --save

使用:

 import PubSub from 'pubsub-js' //引入

 PubSub.publish('delete', data) //发布消息

 PubSub.subscribe('delete', function(data){ }); //订阅

 

demo:

//发布消息  (传递消息)
import PubSub from 'pubsub-js' export default class Search extends Component { search = () => { // 获取用户输入的搜索关键字 const searchData = this.input.value.trim(); if (searchData ){ //发布消息 PubSub.publish('search',searchData) } } }

  

//订阅消息   (接受消息)
import PubSub from 'pubsub-js'

// 在勾子中订阅
componentDidMount(){
  PubSub.subscribe('search',(msg,searchData)=>{
    consolo.log(searchData)
  }
}

  

标签:react,订阅,publish,js,---,searchData,组件,PubSub,pubsub
来源: https://www.cnblogs.com/cjwblogs/p/15387021.html