ES6下子組件調用父組件的方法(推薦)
出于某些目的,最近又開始研究起了RN,看著教程一步步的學習,在最近卻是碰到了一個問題,那就是父子組件的方法調用的問題。
這個問題我百度了很久,JS的ES6語法下,用class創(chuàng)建組件,子組件調用父組件方法模擬器不斷報錯。
因為我看的視頻是基于es5的語法來實現的代碼,所以語法有些不同。
es5的語法下,方法的this都是RN已經幫我們處理好了的,所以按照視頻中的示例是可以達成效果的,但是es6貌似是要自己寫的。。
具體的寫法就是在constructor中添加 this.xxxxx = this.xxxxx.bind(this);
或者在子組件綁定的時候就寫this.xxxxx.bind(this) .
這里就不多講了,下面上代碼,以供需要的人參考。
export default class TestPrj extends Component { constructor(props){ super(props); this.timesReset = this.timesReset.bind(this); this.state = {timex:2}; } timesReset(){ this.setState({ timex:0 }); } render() { return( <View style={styles.container}> <Son ref="Son1" timex={this.state.timex} timesReset={this.timesReset}/> //或者<Son ref="Son1" timex={this.state.timex} timesReset={this.timesReset.bind(this)}/> </View> ); } } class Son extends Component{ constructor(props){ super(props); this.state = {times:this.props.timex}; } componentWillReceiveProps(props){ console.log(this.props); this.setState({ times:props.timex }) } timesReset(){ this.props.timesReset(); } render(){ return( <View style={styles.container}> <Text style={styles.instructions}> 兒子:雖然你揍了我 {this.state.times} 次,但是我 永 不 屈 服?。? </Text> <TouchableHighlight style={styles.btn} underlayColor={'pink'} onPress={this.timesReset.bind(this)}> <Text style={{textAlign:'center'}}>爹,再給你兒子一次機會!!</Text> </TouchableHighlight> </View> ); } }
以上這篇ES6下子組件調用父組件的方法(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
一個類似vbscript的round函數的javascript函數
同vbscript的Round函數功能相同,四舍五入保留指定小數位數2009-04-04javascript另類方法實現htmlencode()與htmldecode()函數實例分析
這篇文章主要介紹了javascript另類方法實現htmlencode()與htmldecode()函數,結合實例形式分析了javascript字符編碼與解碼操作的相關技巧,需要的朋友可以參考下2016-11-11