Home > OS >  onPress event doesn't work on react-native
onPress event doesn't work on react-native

Time:04-10

It shows me only the alert message Idk why. This is the code.

The function that handle signups doesn't Work. I've tried in every manner but I can't solve it. I'm a junior web developer and can't resolve this problem. I should use Hook but I like oop.

class Login extends Component {    

    state = {email: "", password:"", userdata:{}}

    handleSignUp(email,password) {
 
      Alert.alert(  
        'Alert Title',  
        'My Alert Msg',  
        [  
            {  
                text: 'Cancel',  
                onPress: () => console.log('Cancel Pressed'),  
                style: 'cancel',  
            },  
            {text: 'OK', onPress: () => console.log('OK Pressed')},  
        ]  
    );  
}

      


<Button title="Ciao" onPressButton ={this.handleSignUp(this.state.email,this.state.password)} style={styles.button}></Button>
{/*<TouchableOpacity onPress ={this.handleSignUp(this.state.email,this.state.password)} style={styles.button} >
<Text  >Registrati</Text>
  </TouchableOpacity>*/}
        </View>
  )
    }
}

CodePudding user response:

Where do you get your Button component from? The default Button you can import from react-native does not have a onPressButton property. You should try to use onPress

CodePudding user response:

You need to pass function to the onPress prop.

In your example you don't pass a function but its return value cause you are executing it. If you don't pass a function, the onPress has just nothing to execute, it is actually no more than a callback.

You should write something like this:

onPressButton={() => this.handleSignUp(this.state.email,this.state.password)}

Also, as it is a good practice to avoid writing your functions directly in your jsx, you should think about rewrite your function as follow:

handleSignUp() {
      const {email, password} = this.state;
   
      Alert.alert(  
        'Alert Title',  
        'My Alert Msg',  
        [  
            {  
                text: 'Cancel',  
                onPress: () => console.log('Cancel Pressed'),  
                style: 'cancel',  
            },  
            {text: 'OK', onPress: () => console.log('OK Pressed')},  
        ]  
    );
}

Then you can simply write:

onPressButton={this.handleSignUp}
  • Related