Reputation: 245
In the case of this code, I have to click the calculate button twice to find answers of BMI and BMI judge. How to code it to click only once find the two answers?
bmiCalc (){
this.setState({bmi:this.state.weight/(this.state.height*this.state.height)*10000});
if(this.state.bmi<18.5){this.setState({judge: 'Underweight'});}
else if(this.state.bmi<24.9){this.setState({judge:'Normal weight'});}
else if(this.state.bmi<30){this.setState({judge:'Overweight'});}
else{this.setState({judge:'Obesity'});}
}
render(){
return (
<ul><button onClick={this.bmiCalc.bind(this)}>calculate</button></ul>
<ul>BMI: {Math.round(this.state.bmi*10)/10}</ul>
<ul>BMI judge :{this.state.judge} </ul>
);
}
Upvotes: 0
Views: 390
Reputation: 3601
You can do this by calling the set state once at the end of your function:
bmiCalc() {
const bmi = this.state.weight/(this.state.height*this.state.height)*10000;
let judge = 'Obesity';
if(this.state.bmi<18.5){this.setState({judge: 'Underweight'});}
else if(this.state.bmi<24.9){this.setState({judge:'Normal weight'});}
else if(this.state.bmi<30){this.setState({judge:'Overweight'});}
this.setState({bmi: bmi, judge: judge});
}
Upvotes: 0
Reputation: 1006
You could use something like:
function desiredActions (){
action1()
action2()
}
<button onclick={desiredActions}></button>
Basically just wrap the functions you want to call in a function and assign it to the onclick handler.
Note: this isn't specific to React or ES6, just basic JavaScript.
Upvotes: 1