警报提示功能不起作用反应原生 [英] Alert prompt to function not working in react native

查看:79
本文介绍了警报提示功能不起作用反应原生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一个按钮,提示提醒。如果该用户选择,那么我想要运行 exit()函数。但是,它现在编码的方式,由于某种原因没有任何反应。

I have a button on my page that prompts an alert. If that user selects Yes, I then want the exit() function to run. However, the way it is coded now, for some reason nothing happens.

有谁知道我做错了什么?

Does anyone know what I am doing wrong?

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>

    );
  }

}


推荐答案

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

You need to modify promptExit() to an arrow function promptExit = () =>.

使用箭头函数,不要在其体内重新定义 的值,它只是意味着函数体内的与它之外的相同。

因为函数被调用而没有引用特定的对象,如 yourObj.yourMethod(),因此您需要在类中 bind 它构造函数/渲染或使用箭头函数

Since the function is called without its reference to a particular object, like yourObj.yourMethod(), therefore you either need to bind it in the class constructor / render or use arrow function.

没有它,它会丢失它的上下文并始终是 undefined 全局对象

Without it , it would lose it's context and will always be undefined or a global object.

同样,你也可以阅读


何时不使用箭头功能

这篇关于警报提示功能不起作用反应原生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆