React子組件和父組件通訊

React子組件和父組件通訊包括如下幾個方面:ide

  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 });
子組件

對應的this

  1. 子組件Child經過父組件傳入的name,獲取父組件的props
  2. 子組件Child經過父組件傳入的MakeMoney方法調用父組件方法
  3. 父組件Father,經過ref調用子組件的getName方法,獲取props
  4. 父組件Father,經過ref調用子組件的Study方法
相關文章
相關標籤/搜索