警告提示功能在本机反应中不起作用

bry*_*yan 5 javascript reactjs react-native

我的页面上有一个提示警报的按钮。如果该用户选择Yes,那么我希望该exit()函数运行。然而,按照现在的编码方式,由于某种原因什么也没有发生。

有谁知道我做错了什么?

import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, TextInput, Alert } from 'react-native';

type Props = {};
export default class IDScreen extends Component<Props> {

  static navigationOptions = {
    title: 'Identification',
  };

  exit = async () => {
    alert("I should see this but I don't");
    await AsyncStorage.clear();
    this.props.navigation.navigate('Login');
  }

  promptExit() {
    Alert.alert("Are you sure?", "You can't be serious.", [
      {text: 'Yes, Sign out', onPress: async () => this.exit },
      {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
    ],
    { cancelable: true });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.footerText} onPress={this.promptExit}>Sign Out</Text>
      </View>

    );
  }

}
Run Code Online (Sandbox Code Playgroud)

Pri*_*dya 2

您需要修改 promptExit() 为箭头函数promptExit = () =>

使用箭头函数,不是为了在函数体内重新定义 , 的值,它只是this在函数体内部表示与在函数体外部相同的含义。

由于调用该函数时没有引用特定对象(例如 )yourObj.yourMethod(),因此您要么需要bind在 中使用它class constructor / render,要么使用arrow function

没有它,它将失去它的上下文,并且将永远是undefinedor a global object

同样,您还可以阅读

何时不使用箭头函数