兄弟組件傳值 實際上是間接的通過第三方來實現傳值,舉例,第一個兒子把值傳給父親,父親在把這個值傳給第二個兒子,這樣就實現了兄弟組件傳值
來看代碼:
父組件代碼
1 import React from 'react'; 2 import Son1 from './Son1'; 3 import Son2 from './Son2' 4 class Father extends React.Component{ 5 constructor(){ 6 super(); 7 // 先給message一個空值 8 this.state={ 9 message:'' 10 } 11 } 12 // 聲明一個方法用來接收Son1傳來的值 13 message(msg){ 14 this.setState({ 15 message:msg //把Son1傳來的值給message 16 }) 17 } 18 render(){ 19 return( 20 <React.Fragment> 21 {/* 我們在這里引入子組件 拿到上邊聲明的方法 */} 22 <Son1 msg={this.message.bind(this)}></Son1> 23 {/* 這里引入第二個子組件 並聲明一個屬性str 把Son1傳來的值傳過去 */} 24 <Son2 str={this.state.message}></Son2> 25 </React.Fragment> 26 ) 27 } 28 } 29 export default Father;
第一個子組件
1 import React from 'react'; 2 class Son1 extends React.Component{ 3 constructor(){ 4 super() 5 } 6 btn(msg){ 7 // 在這傳給父組件一個值 8 this.props.msg('這是Son1傳過來的') 9 } 10 render(){ 11 return( 12 <React.Fragment> 13 {/* 寫一個點擊按鈕 來調用上邊的值*/} 14 <button onClick={this.btn.bind(this)}>Son1中的按鈕</button> 15 </React.Fragment> 16 ) 17 } 18 } 19 export default Son1;
第二個子組件
1 import React from 'react'; 2 class Son2 extends React.Component{ 3 constructor(){ 4 super() 5 } 6 render(){ 7 return( 8 <React.Fragment> 9 {/* 第二個子組件通過props 這個屬性來接受父組件傳過來的str */} 10 <div>接收Son1的值:{this.props.str}</div> 11 </React.Fragment> 12 ) 13 } 14 } 15 16 export default Son2;
這樣就實現了簡單的兄弟組件傳值