This time I will show you how to call the parent component in ES6. What are the precautions for calling the parent component in ES6? The following is a practical case, let's take a look.
For some purposes, I recently started to study RN again. While watching the tutorials to learn step by step, I recently encountered a problem, that is, the problem of method invocation of parent-child components. I have been asking this question on Baidu for a long time. Under the ES6 syntax of JS, when creating a component using class, the sub-component calls the method of the parent component and the simulator keeps reporting errors. Because thevideo I watched is code based on es5 syntax, so the syntax is somewhat different.
Under the syntax of es5, the this of the method has been handled by RN for us, so the effect can be achieved according to the example in the video, but it seems that es6 needs to be written by ourselves. . The specific way to write it is to add this.xxxxx = this.xxxxx.bind(this);or write this.xxxxx.bind(this) when binding the subcomponent ) .I won’t go into details here, but the code is given below for reference by those who need it.
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> ); } }
What are the commonly used message boxes in JS
js randomly generates 6-digit random numbers
JS method of dynamically creating tags and setting attributes
The above is the detailed content of How to call parent component from child component in ES6. For more information, please follow other related articles on the PHP Chinese website!