Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native Button onPress not working

I'm trying to bind the function handleClick to my button onPress. But it's not working. When I refresh the page, I get the alert without clicking on the button and after I close the alert and click on the button, nothing happens.

My Code is:

class ActionTest extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      thename: 'somename'
    };
  }

  handleClick(){
    alert('Button clicked!');
  }

    render(){
      return(
        <View>
          <Button
           onPress={this.handleClick()}
           title="Click ME"
           color="blue"
          />
        </View> 
        );
    }
}

I'm also getting the warning :

enter image description here

What am I doing wrong?

like image 305
Somename Avatar asked Aug 25 '17 14:08

Somename


2 Answers

First you define your click handler as an arrow function. In this way you don't need to bind the function anymore. Your function will be like this:

handleClick = () => {
    alert('Button clicked!');
}

Then use this function in the <Button> tag like this:

<Button
 onPress={this.handleClick}
 title="Click ME"
 color="blue"
/>
like image 73
Vahid Boreiri Avatar answered Sep 18 '22 02:09

Vahid Boreiri


You are calling handleClick when it renders as you have onPress={this.handleClick()}

try onPress={this.handleClick} instead, to pass it the function as a callback.

like image 44
WayneC Avatar answered Sep 20 '22 02:09

WayneC