You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React嵌套map渲染单选框仅返回首个父元素ID问题

解决嵌套单选框无法获取对应父元素ID的问题

问题根源

  1. 所有单选框未设置name属性分组,浏览器会将所有单选框视为同一组,引发异常的事件触发逻辑
  2. 使用onClick处理单选框状态变化并非最佳实践,建议使用单选框标准的onChange事件

修复后的代码

export const App = () => {
  const array1 = [
    { id: 1, message: "apple" },
    { id: 2, message: "banana" },
    { id: 3, message: "cherry" }
  ];

  const array2 = [
    { id: 4, reply: "mango" },
    { id: 5, reply: "grape" },
    { id: 6, reply: "kiwi" }
  ];

  // 柯里化函数确保正确捕获父元素ID
  const handleChange = (parentId) => () => {
    console.log(parentId);
  };

  return (
    <div>
      {array1.map((parentItem) => (
        <div key={parentItem.id}>
          <span>{parentItem.message}</span>
          {array2.map((childItem) => (
            <div key={childItem.id}>
              <input
                type="radio"
                id={childItem.id}
                name={`reply-group-${parentItem.id}`} {/* 按父元素ID分组单选框 */}
                value={childItem.reply}
                onChange={handleChange(parentItem.id)} {/* 使用标准onChange事件 */}
              />
              <label htmlFor={childItem.id}>{childItem.reply}</label>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
};

关键修改说明

  • 分组单选框:添加name={reply-group-${parentItem.id}},让每个父元素下的单选框属于独立分组,避免跨组干扰
  • 替换事件类型:用onChange替代onClick,这是表单元素状态变化的标准事件,触发逻辑更稳定
  • 柯里化处理函数:通过柯里化确保每次迭代时,函数都能正确捕获当前父元素的ID,规避闭包陷阱导致的参数错误

内容的提问来源于stack exchange,提问作者Vishal Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:42:49