React TypeScript项目中如何将数组map的索引传递给onChange外部函数
我明白你的需求——你想在showDemographicInfo函数里拿到下拉框选中项对应的cbnArray索引,从而直接访问对应元素。其实有两种简洁的方法可以实现,不需要复杂的修改:
方法1:利用select元素的selectedIndex属性(最简单)
HTML的<select>元素本身就有selectedIndex属性,直接返回当前选中项在列表中的索引,完全不需要改动你的option渲染代码。
修改你的showDemographicInfo函数如下:
const showDemographicInfo = (event: React.ChangeEvent<HTMLSelectElement>) => { // 获取选中项的索引 const selectedIndex = event.target.selectedIndex; // 通过索引拿到cbnArray中对应的元素 const selectedItem = cbnArray[selectedIndex]; if (cbnList.length > 1 && cbnState === COMBINED) { setLeftArrowClass(ClassModifier.IN); setRightArrowClass(ClassModifier.IN); } setCbnState(event.target.value); if (event.target.value !== COMBINED) { updateUserId(event.target.value); setCombinedState(false); // 现在可以直接用selectedItem的属性,比如unit setUnit(selectedItem.unit); } else { setCombinedState(true); updateUserId(cbnArray[1]); } console.log("Index: ", selectedIndex, "Selected Item: ", selectedItem); };
你的<select>组件代码完全不需要修改,因为selectedIndex是<select>自带的属性,自动对应你map渲染的option顺序。
方法2:给option添加自定义data-*属性存储索引
如果你需要在option上额外存储更多数据,也可以给每个option添加data-index属性,之后在onChange中读取:
首先修改map中的option渲染:
{cbnArray.map((item: any, index: number) => ( <option key={index} value={item.cbn} data-index={index}> {item.cbn} | {item.unit} | {index} </option> ))}
注意:建议给option加上
key属性(这里用index没问题,因为你的列表是静态或不会重新排序的),符合React的列表渲染规范。
然后修改showDemographicInfo函数:
const showDemographicInfo = (event: React.ChangeEvent<HTMLSelectElement>) => { // 获取选中的option元素 const selectedOption = event.target.options[event.target.selectedIndex]; // 读取data-index属性并转成数字 const index = parseInt(selectedOption.dataset.index || '0', 10); const selectedItem = cbnArray[index]; // 后续逻辑和方法1一致,使用index和selectedItem即可 // ... };
为什么之前的尝试没成功?
因为<select>的onChange事件是绑定在整个select元素上的,而不是单个option,所以没办法直接把map循环中的index作为参数传递给showDemographicInfo。上面两种方法都是通过DOM元素的自带属性或自定义属性,间接获取到选中项的索引。
另外,建议把event的类型从any改成React.ChangeEvent<HTMLSelectElement>,这样TypeScript能提供更好的类型提示,避免潜在错误。
内容的提问来源于stack exchange,提问作者Deepika

