获取 undefined 不是对象(评估 'this.props.url')

Getting undefined is not an Object ( evaluating 'this.props.url')

我正在尝试在我的应用程序中构建一个组件,该组件将在其网站上显示带有 link 的名称,但似乎出现了错误 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;

goToUrl 方法未绑定到组件的实例。

您应该在 class 的构造函数中绑定它,或者将其声明为箭头函数。

// 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 关于事件处理和绑定的内容。