1、PubSub使用方式
1.1 react导入库
npm install pubsub-js --save
1.2 react 页面引入pubsubjs
import PubSub from ‘pubsub-js‘
1.3 pubsubjs使用
发送消息:PubSub.publish(名称,参数)
订阅消息:PubSub.subscrib(名称,函数)
取消订阅:PubSub.unsubscrib(名称)
PS:pubsubjs源码及使用详情https://github.com/mroderick/PubSubJS
2、React实例使用监听实现传参
2.1 子页面home.js使用PubSub.publish发送state
- 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>
- )
- }
- }
- export default Home;
2.2 父页面App.js接收使用PubSub.subscribe订阅指定消息,PubSub.unsubscribe取消订阅消息
- 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进行呈现,此时你会发现它是实时变化的,因为它会实时监听子组件发送的消息。
PS:React-Router4.0建立子父组件关系
子父组件关系建立是依靠React-Router4.0来建立的,附上子父组件关系的源码,若对RR4.0不太了解,可参考http://blog.csdn.net/zfan520/article/details/78563034
- 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>
- )
- }
- }