gpt4 book ai didi

javascript - 使用复选框从数组中添加/删除项目

转载 作者:行者123 更新时间:2023-12-03 09:38:43 25 4
gpt4 key购买 nike

我想在选中复选框时向 state.contacts 数组添加一个项目,并在取消选中复选框时删除该项目。我该如何在 react 中做到这一点?

当前使用发布/订阅模式和回调:

我的组件渲染使用:

handler: function(e) {

channel.publish({
channel: "contact",
topic: "selectedContact",
data: {
id: e.target.attributes['data-ref'].value
}
});
},

return (
<div className="selector">
<input type="checkbox"
checked={isSelected} data-ref={id}
onClick={this.handler} />
</div>
);

我的点击处理程序:

componentDidMount: function() {
var page = this;

this.loadContacts();

// setup subscribe
contactChannel.subscribe("selectedContact", function (data, envelope) {
page.handleSelectedContact(data.id, page);
});
},

handleSelectedContact: function(id, page) {

var page = this;

var callback = function () {

var arrayPush = [];
var arrayPush = page.state.selected.slice();
var index = page.state.selected.indexOf(id);

if (index === -1) {

// if no id in array, push it
arrayPush.push(id);
page.setState({selected: arrayPush})

var idAsNumber = parseInt(id);

// show selected value in checkbox
var newContacts = page.state.contacts.map(function (contact) {
if (contact.id === idAsNumber) {
contact.isSelected = true;
}
return contact;
});

} else {
// remove id from array
page.state.selected.splice(index, 1);
page.setState({selected: arrayPush})

}
// set new contacts state
page.setState({contacts: newContacts});

console.log(page.state.selectedContacts);

basketChannel.publish({
channel: "basket",
topic: "addContactToBasket",
data: {
id: id,
newTotal: arrayPush.length
}
});
}

BasketService.addPerson(id, callback);


},

最佳答案

要在 React 中单击复选框时向数组添加元素,只需向 JSX 标记添加事件处理程序属性,向要访问以获取值的元素添加 ref 属性,然后将项目推送到国家:

getInitialState: function() {
return {isSelected: false, items: []};
},
handler: function(e) {
var isSelected = !this.state.isSelected,
items = this.state.items.push(e.target.value);

this.setState({isSelected: isSelected, items: items});
},
render: function() {
return (
<div className="selector">
<input type="checkbox"
checked={this.state.isSelected}
onChange={this.handler} />
</div>);

关于javascript - 使用复选框从数组中添加/删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31248740/

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