我正在尝试使用状态设置复选框的复选支柱,使用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>
);
}
但是,默认情况下选中复选框后我无法取消选中,有人可以告诉我该怎么做吗?
非常感谢
答案 0 :(得分:2)
在 Key k = KeyFactory.createKey("Employee", 100);
Entity e = new Entity("Employee", k);
函数中,您始终对复选框的状态使用相同的值,但您需要将其反转。
将此添加到handleChange函数:
handleChange
答案 1 :(得分:-1)
问题是因为你使用错误的变量返回。使用{isSelected}
更改{this.state.selected}
应该有效。
getInitialState: function() {
return {
selected:0,
contactId: 0
};
},
render: function() {
var id = this.state.contactId;
var isSelected = this.state.selected;
console.log(isSelected);
return (
<div className="contact-selector">
<input type="checkbox"
checked={this.state.selected}
onChange={this.handleChange} />
</div>
);
}
答案 2 :(得分:-1)
getInitialState: function() {
return {
selected:0,
contactId: 0
};
},
handleChange:function(event){
this.setState({selected: !this.state.selected});
isSelected = this.state.selected;
console.log(isSelected);
}
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>
);
}