这可能是一个简单的问题,但我是 React-Native 的新手,现在完全陷入困境。
如何从函数1调用函数2?
这是我尝试过的,但是当按下第一个按钮时,它会呈现一个错误:
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);
最佳答案
试试这个,
<TouchableOpacity onPress={() => this.function1()}>
<Image source={require('../../../assets/img/button.png')} />
</TouchableOpacity>
与函数表达式相比,粗箭头函数的语法更短,并且在词法上绑定(bind) this 值。箭头函数始终是匿名的,并且可以有效地将function (arguments) { expression }
转换为arguments => expression
。如果在箭头后使用表达式,则返回是隐式的,因此不需要返回。
关于function - 如何在 React-Native 中从另一个函数调用一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018118/