react 兄弟组件传值,发布订阅,使用于任何组件传值,包括vue?

react中兄弟组件传值常规操作一般是,A组件传给父组件,父组件再传给B组件

非常规操作 利用 pubsub-js

  • 在Home组件内调用 PubSub.publish("第一个参数是事件名", 第二个参数是要传递的数据);
 1 import React, { Component } from 'react';
 2 
 3 import PubSub from "pubsub-js";
 4 
 5 class Home extends Component {
 6   constructor(props) {
 7     super(props)
 8     this.state = {
 9       msg: "熊的传值的数据"
10     }
11   }
12   render() {
13     return (
14       <div>
15         首页传值
16         <button onClick={() => {this.send()}}>点击发送</button>
17       </div>
18     );
19   }
20   send = () => {
21     //PubSub.publish向外定义方法名 第一个参数是方法名,第二个参数是传递的数据
22     PubSub.publish("methodName", this.state.msg);
23   }
24 }
25 
26 export default Home;
  • 在兄弟User组件内调用 PubSub.subscribe("methodName", (msg, data) => { }) }

    第一个参数是传递过来的时间名,第二个参数是一个函数: 第一个形参是事件名,第二个形参是传递过来的数据

 1 import React, { Component } from "react";
 2 
 3 import PubSub from "pubsub-js";
 4 
 5 console.log(PubSub)
 6 
 7 class User extends Component {
 8   constructor(props) {
 9     super(props);
10     this.state = {12       value: "",
13     };
14     // 使用PubSub.subscribe接收数据(第一个参数是方法名,)
15     PubSub.subscribe("methodName", (msg, data) => {
16       console.log(data, "pppp");
17       // this.setState({ text: data });
18       this.setState({
19         value: data,
20       });
21     });
22   }
23 
24   render() {
25     return (
26       <div>
27         用户页接收------- {this.state.value}
29       </div>
30     );
31   }
32 
33   getchangevalue = () => {
34 
35   }
36 }
37 
38 export default User;