one 组件
import React, { Component } from 'react' import PubSub from 'pubsub-js' export default class One extends Component { render() { let cities = [ {id: 1, name: '深圳'}, {id: 2, name: '上海'}, {id: 3, name: '武汉'}, {id: 4, name: '杭州'} ] return ( <div className="one"> <h1>one组件</h1> <ul> { cities.map(item=>{ return <li key={item.id} onClick={()=>this.selectCityAction(item.name)}>{item.name}</li> }) } </ul> </div> ) } selectCityAction = (cityName)=>{ console.log(cityName); // 执行发布 PubSub.publish('select-city', cityName); } }
two组件
import React, { Component } from 'react' import PubSub from 'pubsub-js' export default class Two extends Component { state = { oneData: null } render() { return ( <div className="two"> <h1>two组件</h1> <p>接收到的数据为:{this.state.oneData}</p> </div> ) } componentDidMount(){ // 监听 this.token = PubSub.subscribe('select-city', (msg, data)=>{ this.setState({oneData: data}); console.log(data); }); } componentWillUnmount(){ // 移除监听 PubSub.unsubscribe(this.token); } }
App组件
import React, { Component } from 'react'; import One from './components/one' import Two from './components/two' import './style.css' class App extends Component { state = { isShow: true } render() { return ( <div className="App"> <One/> <input type="checkbox" checked={this.state.isShow} onChange={(ev)=>{ this.setState({isShow: ev.target.checked}); }}/> {this.state.isShow && <Two/>} </div> ); } } export default App;
style样式
.App{ padding: 20px; background: lavender; } .one{ padding: 50px; background: lightblue; } .two{ padding: 50px; background: lightcoral; }