当用户选中此复选框时,我能够成功将折扣金额从0%更改为50%,但此后不会关闭。
我假设handleChange
函数有问题:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
// Define data above render()
constructor(){
super();
this.state = {
discount: 0,
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
discount: event.target.checked = this.state.discount = .50});
}
render() {
return(
<div>
Apply 50% discount:
<input type='checkbox' value={this.state.discount} checked={this.state.discount} checked={this.state.discount} onChange={this.handleChange} />
<br/><br/>);
}
}
export default App;
答案 0 :(得分:1)
您似乎在=
函数中缺少handleChange
,导致状态更新的行为不正确。
为清晰和正确起见,请尝试修改此功能:
handleChange(event) {
// Toggle the discount value between 0.5 and 0.0 via this logic
const nextDiscount = (this.state.discount === 0.5) ? 0.0 : 0.5
// Update discount state with nextDiscount value
this.setState({ discount: nextDiscount });
}
另外,请考虑更新您的render()
方法,以便根据checked
的值将this.state.discount
道具的值评估为true / false(即通过该表达式{{1} }。还要确保仅将一个(this.state.discount === 0.5)
属性传递给该复选框输入:
checked