如何将嵌套对象中选中checkbox的对应值传递给Material UI Chip组件
你现在触发checkbox点击事件时仅向上传递了上层的参与人对象,没有传递当前行对应的角色数据,所以无法区分同一个人选中的不同角色,且当前仅存储参与人ID的结构也不能满足chip展示的字段需求,可按以下步骤修改:
第一步:修改Checkbox组件的事件传参
调整循环的key和点击事件入参,把当前行的角色对象也传递给回调:
const checkbox = props.list.map((m) => ( m.involvementRole.map((role) => ( // 给循环项加唯一key避免React警告 <div key={role.involvementRoleId}> <table> <tbody style={{ width: "100%" }}> <tr> <td style={{ width: "60px" }}> <input type="checkbox" id = {role.involvementRoleDescription} // 同时传递参与人对象和当前角色对象 onClick={() => props.handleCheckboxChange(m, role)} /> </td> <td style={{ width: "250px" }} value={role.involvementRoleDescription}> {role.involvementRoleDescription} </td> <td style={{ width: "250px" }}> {m.client.firstName + " " + m.client.lastName} </td> </tr> </tbody> </table> </div> )) ));
另外注意你代码里的<typography>组件首字母小写了,Material UI的Typography组件是大写开头,否则样式会不生效。
第二步:调整选中状态存储逻辑
将原来仅存储ID的数组,修改为存储包含所有所需字段的对象数组,用唯一的角色ID做去重判断:
const handleCheckboxChange = (participant, role) => { setParticipants((currentParticipants) => { // 用唯一的角色ID判断当前项是否已选中 const isSelected = currentParticipants.some(item => item.roleId === role.involvementRoleId) if (isSelected) { // 已选中则移除对应项 return currentParticipants.filter(item => item.roleId !== role.involvementRoleId) } else { // 未选中则新增包含所有展示所需字段的对象 return [...currentParticipants, { key: role.involvementRoleId, // 直接匹配chip删除逻辑需要的key roleId: role.involvementRoleId, roleDesc: role.involvementRoleDescription, firstName: participant.client.firstName, lastName: participant.client.lastName }] } }) };
第三步:直接复用数据渲染chip
现在claimParticipants数组里已经包含了所有需要的字段,handleSubmit赋值后,渲染chip时直接取对应字段即可:
// 渲染chip示例 {chipData.map(chip => ( <Chip key={chip.key} label={`${chip.roleDesc} - ${chip.firstName} ${chip.lastName}`} onDelete={handlePerformerDelete(chip)} /> ))}
内容的提问来源于stack exchange,提问作者MinMin240
相关产品推荐
相关产品推荐

