React中兄弟组件传值

兄弟组件传值 实际上是间接的通过第三方来实现传值,举例,第一个儿子把值传给父亲,父亲在把这个值传给第二个儿子,这样就实现了兄弟组件传值

来看代码:

父组件代码

 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;    

这样就实现了简单的兄弟组件传值

猜你喜欢

转载自www.cnblogs.com/z-j-c/p/12072278.html