React子組件和父組件通信


React子組件和父組件通信包括以下幾個方面:

  1. 子組件獲取父組件屬性:props或者state
  2. 子組件調用父組件的方法
  3. 父組件獲取子組件的屬性:props或者state
  4. 父組件調用子組件的方法

我們從下面這個例子來詳細了解:

 1 var Father=React.createClass({
 2     getDefaultProps:function(){
 3         return {
 4             name:"父組件"
 5         }
 6     },
 7     MakeMoney:function(){ // 掙錢,供子組件調用
 8         alert("我在掙錢!");
 9     },
10     CheckStudy:function(){ // 學習,調用子組件方法
11         this.refs["child"].Study();
12     },
13     getChildName:function(){ // 調用子組件方法獲取孩子名字
14         alert(this.refs["child"].getName());
15     },
16     render:function(){
17         
18         return <div>
19                     <button onClick={this.CheckStudy}>監控孩子學習</button>
20                     <button onClick={this.getChildName}>獲取孩子名字</button>
21                     <br/>
22                     子組件
23                     <Child ref="child" fatherName={this.props.name} MakeMoney={this.MakeMoney}></Child>
24                 </div>;
25     }
26 });
父組件
 1 var Child=React.createClass({
 2     getDefaultProps:function(){
 3         return {
 4             name:"子組件"
 5         }
 6     },
 7     StudyMakeMoney:function(){ // 學習掙錢,調用父組件方法
 8         this.props.MakeMoney();
 9     },
10     Study:function(){ // 學習,調用子組件方法
11         alert("我在學習!");
12     },
13     getName:function(){// 供父組件調用,返回名字
14         return this.props.name;
15     },
16     render:function(){
17         
18         return <div>父組件名字:{this.props.fatherName}<button onClick={this.StudyMakeMoney}>孩子學習掙錢</button></div>;
19     }
20 });
子組件

對應的

  1. 子組件Child通過父組件傳入的name,獲取父組件的props
  2. 子組件Child通過父組件傳入的MakeMoney方法調用父組件方法
  3. 父組件Father,通過ref調用子組件的getName方法,獲取props
  4. 父組件Father,通過ref調用子組件的Study方法


免責聲明!

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



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