gpt4 book ai didi

reactjs - React Checkbox 组件需要点击两次才能更改为选中状态

转载 作者:行者123 更新时间:2023-12-04 00:02:19 38 4
gpt4 key购买 nike

我有一个呈现复选框的 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;

那么我需要做什么才能使复选框一键变为选中状态并一键变为未选中状态?

最佳答案

更改状态时,您不应直接访问旧状态,例如

this.setState({ checked: !this.state.checked });

而是做

this.setState(({ checked }) => ({ checked: !checked }));

或者您从 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>
);
}

关于reactjs - React Checkbox 组件需要点击两次才能更改为选中状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58719791/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com