Tuesday, October 20, 2020

Binding an event to a button

 here, we want to link a function to a button component so that when it is called, this function/method is called.


For that, we need to "bind".


 <button onClick={this.getRandomeNumber}>Random Number</button>

<Numbers myNumber={this.state.r}/>


Inside component itself define method.


constructor(props){

super(props);

this.state={

r: 0

}

this.getRandomNumber = this.getRandomNumber.bind(this);

//we can bind like this or we can bind directly in the jsx code by appending bind keyword onClick={this.getRandomNumber.bind}, but this require binding for each call or wherever we use.

}


getRandomNumber(){

console.log("called random number");

this.setState({r: Math.floor(Math.random()*100})

}


another component class Numbers

---

in rendor jsx.

{this.props.myNumber}


No comments:

Post a Comment