我有一个表单组件,它将有状态数组中的所有contacts
显示为复选框选项。 选中关联的复选框后,应将联系人传递到 newGroup.groupContacts
中,如果未选中,也应将其删除。语法是什么,包括在handleCheckbox
中执行此操作?
const CreateGroupForm = props => {
const defaultForm = { id: null, groupName: '', groupContacts: [] }
const [newGroup, setNewGroup] = useState(defaultForm)
const handleInputChange = event => {
const { name, value } = event.target
setNewGroup({ ...newGroup, [name]: value })
}
const handleCheckbox = event => {
console.log('called')
const {value} = event.target
console.log(event.target)
setNewGroup({...newGroup, groupContacts: [...newGroup.groupContacts, value] })
}
const handleSubmit = event => {
event.preventDefault()
if (!newGroup.groupName || !newGroup.groupContacts) return
props.addGroup(newGroup)
setNewGroup(defaultForm)
}
return (
<div>
<h2>Create a Group</h2>
<Form onSubmit={handleSubmit}>
<Form.Group >
<Form.Label>Group Name</Form.Label>
<Form.Control
type="text"
name="firstName"
onChange={handleInputChange}
placeholder="First Name"
value={newGroup.name}
/>
</Form.Group>
<Form.Group >
{props.contacts.map(contact => (
<div className="mb-3" key={contact.id}>
<Form.Check
onChange={handleCheckbox}
type='checkbox'
label={`${contact.firstName} ${contact.lastName}`}
value={contact}
/>
</div>
))}
</Form.Group>
<Button type="submit">Submit</Button>
<Button>Cancel</Button>
</Form>
</div>
)
}
export default CreateGroupForm
所以,看看你的函数,我想它正在将其添加到状态中,而不是用于删除它。
- 至于您的
Form.Check
元素,传递 id 而不是整个联系人:
<Form.Check
onChange={handleCheckbox}
type='checkbox'
label={`${contact.firstName} ${contact.lastName}`}
value={contact.id}
/>
- 处理事件检查/取消选中:
const handleCheckbox = event => {
const { value } = event.target;
const intValue = parseInt(value, 10);
let newGroupContacts = [...newGroup.groupContacts];
const contactExists = newGroupContacts.find(contact => contact.id === intValue);
if (contactExists) {
newGroupContacts = newGroupContacts.filter(contact => contact.id !== intValue);
} else {
const contact = props.contacts.find(contact => contact.id === intValue)
newGroupContacts = [...newGroupContacts, contact];
}
setNewGroup({...newGroup, groupContacts: newGroupContacts });
}
我希望代码正在解决问题并且对您来说是可读的。