我有一个呈现复选框的 React 组件。问题是需要单击两次才能变为选中状态,然后单击两次才能变为未选中状态。
JS:
import React, { Component } from "react";
class CheckboxRow extends Component {
constructor(props) {
super(props);
this.state = { checked: false };
}
inputChangedHandler() {
this.setState({ checked: !this.state.checked });
}
render() {
return (
<div className="checkbox-row">
<input
id={this.props.id}
type="checkbox"
onChange={() => this.inputChangedHandler()}
checked={this.state.checked}
/>
<label htmlFor={this.props.id} className="checkbox-row__label">
Label goes here
</label>
</div>
);
}
}
export default CheckboxRow;
Run Code Online (Sandbox Code Playgroud)
那么我需要做什么才能使复选框一键变为选中状态,一键变为未选中状态?
更改状态时不应直接访问旧状态,例如
this.setState({ checked: !this.state.checked });
Run Code Online (Sandbox Code Playgroud)
相反做
this.setState(({ checked }) => ({ checked: !checked }));
Run Code Online (Sandbox Code Playgroud)
或者您从 onChange 访问传递的事件。这里写成一个较短的功能组件
function CheckboxRow({ id }) {
const [checked, setChecked] = useState(false);
const onChange = event => {
event.persist();
setChecked(event.target.checked);
};
return (
<div className="checkbox-row">
<input id={id} type="checkbox" onChange={onChange} checked={checked} />
<label htmlFor={id} className="checkbox-row__label">
Label goes here
</label>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)