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>
- )
- }
- }