我正在尝试在我的应用程序中构建一个组件,该组件将显示一个带有网站链接的名称,并且似乎收到错误Getting undefined is not an Object ( evaluating 'this.props.url')
。我试图通过添加.bind(this)
来解决此问题,但它会导致语法错误或相同的错误。
这是组件的代码
import React, { Component } from "react";
import { Linking, Text, StyleSheet, TouchableHighlight } from "react-native";
const styles = StyleSheet.create({
sciName: {
textAlign: "center",
fontWeight: "bold",
color: "black"
}
});
class LinkedName extends Component<Props> {
render() {
const { latinName } = this.props;
return (
<TouchableHighlight
onPress={this.goToUrl}
hitSlop={{ top: 50, left: 50, bottom: 50, right: 50 }}
>
<Text style={styles.sciName}>{latinName}</Text>
</TouchableHighlight>
);
}
goToUrl() {
const { url } = this.props;
Linking.canOpenURL(url)
.then(supported => {
if (supported) {
Linking.openURL(url);
} else {
alert("cannot open this link");
}
});
}
}
export default LinkedName;
答案 0 :(得分:1)
goToUrl
方法未绑定到组件的实例。
您应该将其绑定到类的构造函数中,或者将其声明为箭头函数。
// Arrow function declaration
goToUrl = () => {
const { url } = this.props;
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.openURL(url);
} else {
alert('cannot open this link');
}
});
};
看看React's documentation有关事件处理和绑定的信息。