0

I have a simple app with a Welcome class that redirects to Select class. Select class has 2 buttons.

My problem is that when I redirect to Select class, button are automatically clicked and I have the Alert triggered without clicking.

Do you know how to prevent it ?

//Select.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image,ImageBackground, Linking, TouchableOpacity, Alert, Button } from 'react-native';
import { createStackNavigator, createAppContainer } from "react-navigation"

export default class Select extends React.Component {

  displayMessage1(){
    Alert.alert("hello1")
  }

  displayMessage2(){
    Alert.alert("hello2")
  }

  render() {
    return (
        <View>
          <ImageBackground
              source={require("./images/im1.jpg")}
              style={styles.imageBackground}>

                <View style ={{flex:0.3}}></View>

                <View style ={{flex:1}}>
                    <Text style ={styles.text}> myText</Text>
                </View>

                <Button
                  onPress={this.displayMessage1()}
                  title="go message 1"
                  color="#00aaf0"
                />

                <View style ={{flex:0.3}}></View>

                <Button
                  onPress={this.displayMessage2()}
                  title="go message 2"
                  color="#00aaf0"
                />

                <View style ={{flex:1}}></View>

          </ImageBackground>
        </View>
    )
  }
}
```

2 Answers 2

1

You are executing displayMessage1 message on the onClick method of your button.

You should do something like, so when the event is fired, the method binded to your class will be called.

<Button
    onPress={this.displayMessage1.bind(this)}
    title="go message 1"
    color="#00aaf0"
    />

Sign up to request clarification or add additional context in comments.

Comments

1
<Button
  onPress={this.displayMessage1()} // <-- here
  title="go message 1"
  color="#00aaf0"
/>

That's be cause instead of passing a reference to the the onPress prop you are actually execution the method, so on every render that method if being called.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.