undefined is not an object(evaluating '_this2.

2020-07-27 05:53发布

问题:

I need to do an alert, when the alert is pressed, i need to go to other screen, but, expo show me that error, this is my code

    AlertaDi(){

      Alert.alert(
      'Alert Title',
      'Correcto',
      [
        {text: '==>', onPress: () => 
        this.props.navigation.navigate('InicioBot')}
      ],
    );

  }

if i use

onPress={() => this.props.navigation.navigate('InicioBot')} 

in a button, it works, but i need that navigation in an event

回答1:

Try this:

AlertaDi = () => {
  Alert.alert('Alert Title', 'Correcto', [
    { text: '==>', onPress: () => this.props.navigation.navigate('InicioBot') },
  ]);
};

Convert your anonymous function into an arrow function to get this context of its parent



回答2:

I found another solution, in onPress of the button you may to put

onPress={() => this.AlertaDi(this.props.navigation)}

like this

<View style={{width:'15%', height:'70%', margin: 10 }}>

  <Button onPress={() => this.AlertaDi(this.props.navigation)}
  title="Niños"/>

</View>

This is the code

import React from 'react';
import { 
  View, 
  StyleSheet,
  Button,
  Alert,
 } from 'react-native';

export default class TallerBotonDo extends React.Component {

 AlertaDi(){

      Alert.alert(
      'Alert Title',
      'Correcto',
      [
        {text: '==>', onPress: () => this.props.navigation.navigate('InicioBot')}
      ],
    );

 }
 render() {

  return (
   <View style={{width:'45%', height:'45%', margin: 10 }}>

    <Button onPress={() => this.AlertaDi(this.props.navigation)}
     title="Niños"/>

   </View>

  );

 }

}