1、react中的消息发布订阅模式 – publish和subscribe
调度中心 bus
export let bus = {
list: [],
// 订阅者, 用于接受消息
subscribe(callback) {
this.list.push(callback);
},
// 发布者,用于发布消息
publish(value) {
this.list.forEach(callback => {
callback && callback(value);
})
}
}
在不同的组件中使用,实现组件之间的通讯
import { bus } from "./bus.js"
// 接收消息
bus.subscribe((val) => {
console.log(val); // 订阅者接收到的消息
})
// 点击按钮发布消息
handleClick() {
bus.publish('要发出去的消息');
}
2、context方案 (稍微麻烦,react官方提供)-- 生产者provider 消费者consumer
// 1、创建context上下文
const Context = React.createContext();
// 2、包裹服务商生产者
// 在父组件中
export default class App extends React.Component{
state = {
info: ''
}
render() {
return(
<Context.Provider value={{ info: this.state.info, setInfo: (val) => { this.setState({ info: val }) } }}>
// 父组件里面自己的业务
</Context.Provider>
)
}
}
// 兄弟组件(发消息)
render() {
return(
<Context.Consume>
{
(val) => {
return(
<button onClick={ () => { val.setInfo('传过去的值') } }>点击传值到兄弟组件</button>
)
}
}
</Context.Consume>
)
}
// 兄弟组件(接消息)
render() {
return(
<Context.Consume>
{
(val) => {
return(
<div>{val.info}</div>
)
}
}
</Context.Consume>
)
}
完整代码如下
import React from 'react';
/**
* context 实现组件之间的通讯
*
*
*/
// 创建 context 对象
const Context = React.createContext();
class App1 extends React.Component {
render() {
return(
<Context.Consumer>
{ (val) => {
return(
<div>
兄弟1,发送数据
<button onClick={ () => {
val.changeInfo("兄弟1要发出的数据");
} }>点击发送数据</button>
</div>
)
} }
</Context.Consumer>
)
}
}
class App2 extends React.Component {
render() {
return(
<Context.Consumer>
{ (val) => {
console.log(val.info);
return(
<div>
兄弟2-- {val.info}
</div>
)
} }
</Context.Consumer>
)
}
}
export default class App extends React.Component {
state = {
info: ''
}
render() {
return(
<Context.Provider value={{
info: this.state.info,
changeInfo: (val) => {
this.setState({
info: val
})
}
}}>
<div>
<App1></App1>
<App2></App2>
</div>
</Context.Provider>
)
}
}