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;