React子組件和父組件通訊包括如下幾個方面:ide
咱們從下面這個例子來詳細瞭解:學習
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