Reputation: 459
This might be an easy question, but I'm new to React-Native and I'm totally stuck right now.
How do I call function2 from function1?
This is what I've tried, but when pressing the first button it renders an error that says:
Undefined is not a function (evaluating 'this.function2()')
import React, { Component } from 'react';
import {
AppRegistry,
View,
Image,
TouchableOpacity,
} from 'react-native';
export default class Example extends Component {
function1(){
console.log('function1() called');
...
this.function2();
};
function2() {
console.log('function2() called');
...
};
render() {
return (
<View>
<TouchableOpacity onPress={this.function1}>
<Image source={require('../../../assets/img/button.png')} />
</TouchableOpacity>
<TouchableOpacity onPress={this.function2}>
<Image source={require('../../../assets/img/button.png')} />
</TouchableOpacity>
</View>
);
};
}
AppRegistry.registerComponent('Example', () => Example);
Upvotes: 3
Views: 13246
Reputation: 260
Try this,
<TouchableOpacity onPress={() => this.function1()}>
<Image source={require('../../../assets/img/button.png')} />
</TouchableOpacity>
fat arrow functions have a shorter syntax compared to function expressions and lexically bind the this value. Arrow functions are always anonymous and effectively turn function (arguments) { expression }
into arguments => expression
. If using an expression after an arrow, the return is implicit, so no return is required.
Upvotes: 4
Reputation: 847
if the function is a callback and will pass to another component, you should bind them in your component constructer.
constructor(props) {
super(props);
this.function1 = this.function1.bind(this);
this.function2 = this.function2.bind(this);
}
Upvotes: 4