React中父子組件傳值


一.首先我們先來看父組件向子組件傳值

1.1 我們要明白父組件 --> 子組件 是通過props這個屬性來傳值的

我們來看父組件的代碼

 1 import React from 'react'; 
 2 import Son1 from './Son1';
 3 class Father extends React.Component{
 4     constructor(){
 5         super();
 6        
 7     }
 8     render(){
 9         return(
10             <React.Fragment>
11                 {/* 我們在這里引入子組件 並聲明一個屬性str  給他傳一個hello */}
12                 <Son1 str='hello'></Son1>
13             </React.Fragment>
14         )
15     }
16 
17 }
18 export default Father;

接着看子組件

 1 import React from 'react';
 2 class Son1 extends React.Component{
 3     constructor(){
 4         super()
 5     }
 6 
 7     render(){
 8         return(
 9             <React.Fragment>
10                 {/* 子組件通過props 這個屬性來接受父組件傳過來的str */}
11                 {this.props.str}
12             </React.Fragment>
13         )
14     }
15 
16 }
17 export default Son1;

頁面上就可以得到 hello這個值

二. 子組件向父組件傳值

在這里我們分為4個步驟

2.1、在父組件中聲明一個函數,用於接收子組件的傳值

2.2、通過組件屬性的方法,把函數傳遞給子組件

先看父組件的代碼

 1 import React from 'react';  
 2 import Son1 from './Son1';
 3 class Father extends React.Component{
 4     constructor(){
 5         super();
 6        
 7     }
 8     // 1、在這里中聲明一個函數,用於接收子組件的傳值
 9     message(msg){
10         // 通過形參接受到子組件的值並打印到控制台  
11         console.log(msg)
12     }
13     render(){
14         return(
15             <React.Fragment>
16               {/* 在這里聲明一個msg屬性,通過組件屬性的方法,把函數傳遞給子組件 */}
17                 <Son1 msg={this.message}></Son1>
18             </React.Fragment>
19         )
20     }
21 
22 }
23 export default Father;

2.3、在子組件中通過props屬性調用父組件的函數,並通過參數傳值

 1 import React from 'react';
 2 class Son1 extends React.Component{
 3     constructor(){
 4         super()
 5     }
 6     render(){
 7         return(
 8             <React.Fragment>
 9             {/* 在子組件中通過props屬性調用父組件的函數,並通過參數傳值 */}
10                 {this.props.msg('hello Word')}
11             </React.Fragment>
12         )
13     }
14 
15 }
16 export default Son1;

2.4、在父組件中的函數通過形參接收子組件的傳值

這樣就可以看到控制台打印的效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM