this.nameOfFunction在调用时不是函数

时间:2019-04-10 12:53:55

标签: react-native

我已经在react native中发出了一条警告消息,单击它会调用一个函数。但是我收到错误消息:

  

_this.function1不是函数。(在'_this.goToMapBack('1')'中,'_ this.goToMapBack'未定义)

  alertFunction(){
    Alert.alert(
      "Text Message",
      [
        {
          text: 'Yes',
          onPress: this.function1('1'),
        },
        {
          text: 'No',
          onPress: this.function1('2'),
        },
      ],
      {cancelable: false},
    );
  }

  function1(value){
    if (value =='1') {
      var url = "XXXXX";
    }
    else{
      var url = "YYYYY"
    }
    Linking.openURL(url);
  }

  render() {
    const valueNb = navigation.getParam('valNb', '1');
    return (
        <View>
                <Button
                      onPress={this.alertFunction.bind(valueNb)}
                      title="qwerty"
                      color="#ffffff"
                    />

我还测试了 onPress:function1('1') onPress:()=> this.function1('1'),但功能始终未定义。

您知道如何纠正它吗?

1 个答案:

答案 0 :(得分:2)

将您的匿名函数转换为箭头函数以获得this上下文:

  

箭头功能自动绑定到其父级(您无需   明确绑定它)...因为它没有它自己的上下文

class Comp {
  alertFunction = () => {
    Alert.alert(
      "Text Message",
      [
        {
          text: "Yes",
          onPress: this.function1("1")
        },
        {
          text: "No",
          onPress: this.function1("2")
        }
      ],
      { cancelable: false }
    );
  };

  function1 = value => {
    if (value == "1") {
      var url = "XXXXX";
    } else {
      var url = "YYYYY";
    }
    Linking.openURL(url);
  };

  render() {
    const valueNb = navigation.getParam("valNb", "1");
    return (
      <View>
        <Button onPress={this.alertFunction} title="qwerty" color="#ffffff" />
      </View>
    );
  }
}

如果您选择使用匿名功能

您需要在构造函数中绑定函数...因为 Anonymous Function 具有它自己的上下文...这就是为什么您需要告诉它使用您的this上下文组件

  

当您将匿名函数传递给on时,可以绑定它   按 。但不建议使用,因为它将创建一个新的   每次调用函数的副本

class Comp {
  constructor(props) {
    super(props);

    this.function1 = this.function1.bind(this);
    this.alertFunction = this.alertFunction.bind(this);
  }

  alertFunction() {
    Alert.alert(
      "Text Message",
      [
        {
          text: "Yes",
          onPress: this.function1("1")
        },
        {
          text: "No",
          onPress: this.function1("2")
        }
      ],
      { cancelable: false }
    );
  }

  function1(value) {
    if (value == "1") {
      var url = "XXXXX";
    } else {
      var url = "YYYYY";
    }
    Linking.openURL(url);
  }

  render() {
    const valueNb = navigation.getParam("valNb", "1");
    return (
      <View>
        <Button onPress={this.alertFunction} title="qwerty" color="#ffffff" />
      </View>
    );
  }
}