1安装
npm install pubsub-js
2 父页面 放2个组件
import React, { Component } from "react";
import Header from "./view/todolist/header";
import List from "./view/todolist/list";
export default class App extends Component {
render() {
return (
<div style={{ border: "1px solid red" }}>
<h5 style={{ color: "red" }}>容器壳子</h5>
<Header />
<List />
</div>
);
}
}
3 子组件header发布消息
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class Header extends Component {
onKeyUp=(e)=>{
if(e.keyCode===13){
//发布消息
PubSub.publish('headerKeyWord',e.target.value)
}
}
render() {
return (
<div className='header' style={{ border: "1px solid blue" }}>
<h5 style={{ color: "blue" }}>子组件header</h5>
<input placeholder='请输入按回车确认' onKeyUp={this.onKeyUp} />
</div>
)
}
}
3 子组件list订阅消息
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class List extends Component {
state={
KeyWord:''
}
componentDidMount(){
this.tokens= PubSub.subscribe('headerKeyWord',(_,data)=>{
console.log('header传递过来的数据',data)
this.setState({
KeyWord:data
})
})
}
// 组件卸载时取消订阅
componentWillUnmount(){
PubSub.unsubscribe(this.tokens)
}
render() {
return (
<div style={{ border: "1px solid blue" }}>
<h5 style={{ color: "blue" }}>子组件list{this.state.KeyWord}</h5>
<h5 style={{ color: "blue" }}>子组件list{this.state.KeyWord}</h5>
<h5 style={{ color: "blue" }}>子组件list{this.state.KeyWord}</h5>
</div>
)
}
}