PubSub使用方式

1、react导入库

1
npm install pubsub-js --save

2、react 页面引入pubsubjs

1
import PubSub from 'pubsub-js'

3、pubsubjs使用
发送消息:PubSub.publish(名称,参数)
订阅消息:PubSub.subscrib(名称,函数)
取消订阅:PubSub.unsubscrib(名称)
PS:pubsubjs源码及使用详情https://github.com/mroderick/PubSubJS

React实例使用监听实现传参

1、子页面home.js使用PubSub.publish发送state

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React, { Component } from 'react';  
import PubSub from 'pubsub-js';
class Home extends Component {
constructor(props){
super(props);
this.state={
increase:'increase',
decrease:'decrease'
}
}
buttonIncrease(){
PubSub.publish('PubSubmessag',this.state.increase);
}
buttonDecrease(){
PubSub.publish('PubSubmessage', this.state.decrease);
}
render() {
return (
<div>
Some state changes:
<button onClick={this.buttonIncrease.bind(this)}>Increase</button>
<button onClick={this.buttonDecrease.bind(this)}>Decrease</button>
</div>
)
}
}

2、父页面App.js接收使用PubSub.subscribe订阅指定消息,PubSub.unsubscribe取消订阅消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import React, { Component } from 'react';  
import { Link} from 'react-router-dom';
import PubSub from 'pubsub-js';

export default class App extends Component{
constructor(props){
super(props);
this.state={
increase:'none',
}
}
componentDidMount(){
this.pubsub_token = PubSub.subscribe('PubSubmessage', function (topic,message) {
this.setState({
increase: message
});
}.bind(this));
}
componentWillUnmount(){
PubSub.unsubscribe(this.pubsub_token);
}
render() {
return (
<div>
<header>
Links:
<Link to="/App/home">Home</Link>
</header>
<div style={{ marginTop: '1.5em' }}>{ this.props.children}</div>
<div style={{ marginTop: '1.5em' }}>{ this.state.increase}</div>
</div>
)
}
}

当在子页面单击increase、decrease按钮,会发送不同的消息给父页面,父页面收到消息,利用this.state.increase进行呈现,此时你会发现它是实时变化的,因为它会实时监听子组件发送的消息。

React-Router4.0建立子父组件关系

子父组件关系建立是依靠React-Router4.0来建立的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React, { Component } from 'react';  
import {BrowserRouter } from 'react-router-dom';
import { Router, Route, } from 'react-router'

import App from '../components/App.js'
import Home from '../components/Home.js'

export default class RouterIndex extends Component {
render() {
return (
<BrowserRouter>
<App path="/App" component={App}>
<Route path="/App/home" component={Home} />
</App>
</BrowserRouter>
)
}
}