警报提示功能不起作用反应原生

时间:2018-03-31 19:47:43

标签: 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>

    );
  }

}

2 个答案:

答案 0 :(得分:3)

尝试此方法将有效

从Button调用Alert.alert()函数,而不是在另一个函数内部调用,它将起作用,只需查看代码片段即可。 exit 是一个箭头函数,而不是 this.exit ,而是这样的“ this.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');
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.footerText} 
  onPress={
    () => 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 });
  }

   }>Sign Out</Text>
    </View>

    );
  }

}

答案 1 :(得分:0)

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

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

由于调用函数时没有引用特定对象,例如yourObj.yourMethod(),因此您需要在bindclass constructor / render或使用arrow function。< / p>

如果没有它,它将失去它的上下文,并始终是undefinedglobal object

同样,您也可以阅读

  

When not to use arrow functions