[英]Add/ remove item from array using checkbox
I would like to add an item to the state.contacts array when a checkbox is checked, and remove the item when a checkbox is unchecked. 我想在选中复选框时将一项添加到state.contacts数组中,而在取消选中复选框时将其删除。 How would I do this in react? 我将如何做出反应?
Currently using a pub/ sub pattern and callbacks: 当前使用pub / sub模式和回调:
My component renders using: 我的组件使用以下方式渲染:
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>
);
My click handler: 我的点击处理程序:
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);
},
To add an element to an array when clicking a checkbox in React, you just add an event handler attribute to the JSX tag, add a ref attribute to the elements you want to access for getting values, and then push an item to the state: 要在单击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>);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.