this.nameOfFunction在调用它时不是函数

问题描述 投票:0回答:1

我已经做出反应原生的警报消息,当点击它时调用一个函数。但我有错误信息:

_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')但函数总是未定义的。

你知道怎么纠正吗?

react-native
1个回答
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>
    );
  }
}

如果您选择使用匿名功能

你需要在构造函数中绑定你的函数...因为匿名函数有它自己的上下文...这就是为什么你需要告诉它使用你的组件的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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.