Reputation: 121
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>
)
}
}
```
Upvotes: 0
Views: 1875
Reputation: 5226
<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.
Upvotes: 1
Reputation: 2836
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"
/>
Upvotes: 1