pubsub-js事件的發布和訂閱
- 2020 年 5 月 22 日
- 筆記
- javascript
pubsub-js事件的發布和訂閱
1.介紹:一個優秀的js訂閱事件和發布事件的庫,通常用於組件與組件之間的傳值
// 安裝使用 npm i pubsub-js yarn add pubsub-js // 在React中使用 // pages/search/index.js組件 import PubSub from 'pubsub-js' import Child from '../../components/child/index' class Index extends React.PureComponent { constructor (props) { super(props) this.state = {} } publishEvent = () => { // 訂閱事件 PubSub.publish('zhangxuedong', '用戶密碼是:18532620986') // 取消某一個事件的發布 // PubSub.unsubscribe('zhangxuedong') // 取消事件事件的腹部 //PubSub.clearAllSubscriptions() // 獲取發布的事件名稱 // PubSub.getSubscriptions('zhangxuedong') } render () { <div> <Child /> <button onClick={ this.publishEvent }>點擊發布事</button> </div> } } // components/child/index組件 import PubSub from 'pubsub-js' class Index extends React.PureComponent { componentDidMount () { // 訂閱事件,第一個參數是事件名稱,第二個參數是傳遞的數據 PubSub.subscribe('zhangxuedong', (data, msg) => { console.log(data, msg) }) } render () { return ( <div>我是子組件</div> ) } }