gpt4 book ai didi

javascript - ReactJs 复选框 - 无法取消选中

转载 作者:行者123 更新时间:2023-11-30 00:24:44 25 4
gpt4 key购买 nike

我正在尝试使用状态设置复选框的 checked 属性,使用 handleChange 函数更新代码:

getInitialState: function() {
return {
selected:0,
contactId: 0
};
},

handleChange: function(e) {
var id = this.state.contactId;

console.log(e.target.checked);

if (e.target.checked === true){

console.log('selected');

contactChannel.publish({
channel: "contact",
topic: "selectedContact",
data: {
id: [id]
}});

} else{

basketChannel.publish({
channel: "basket",
topic: "removePersonFromBasket",
data: {
id: [id]
}
});


console.log('deselected flag');


}
},
render: function() {

var id = this.state.contactId;
var isSelected = this.state.selected;

console.log(isSelected);

return (
<div className="contact-selector">
<input type="checkbox"
checked={isSelected}
onChange={this.handleChange} />
</div>
);
}

但是,一旦默认选中该复选框,我就无法取消选中它,谁能告诉我该怎么做?

非常感谢

最佳答案

handleChange 函数中,您始终为复选框的状态使用相同的值,但您需要将其反转。

将此添加到您的 handleChange 函数中:

handleChange:function(event){
this.setState({selected: !this.state.selected}); //look at the !NOT sign

}

关于javascript - ReactJs 复选框 - 无法取消选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849994/

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