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

如何在select事件触发时获取option的key值并用于条件判断?

获取Select选择项对应的id值(React)

React里的key属性是框架内部用来优化渲染的,不会被渲染到实际DOM节点上,所以你用event.target.key根本拿不到对应的值。下面给你几种可行的解决方案:

方案1:给option设置value属性存id

把每个option的value设为对应的localState.id,这样在select的change事件里,直接通过event.target.value就能拿到id,记得转成数字类型(因为value默认是字符串)。

修改后的代码:

export default function unitFunc(){
  const lenghtArray = [
    { id: 1, value: "meter" },
    { id: 2, value: "kilometer" },
    { id: 3, value: "centimetre" },
    { id: 4, value: "milimetre" },
    { id: 5, value: "mile" },
    { id: 6, value: "yard" },
  ];

  const selectConversion = (event) => {
    const selectedId = Number(event.target.value);
    console.log(selectedId);
    // 这里就可以用selectedId做条件判断了
    if(selectedId === 1){
      // 处理meter的逻辑
    }
  };

  return (
    <select onChange={selectConversion}>
      {lenghtArray.map((localState) => (
        <option key={localState.id} value={localState.id}>
          {localState.value}
        </option>
      ))}
    </select>
  )
}

方案2:使用data属性存储id

给option添加自定义的data-id属性,然后通过event.target.dataset.id获取对应的值,同样需要转成数字。

代码示例:

export default function unitFunc(){
  const lenghtArray = [
    { id: 1, value: "meter" },
    { id: 2, value: "kilometer" },
    { id: 3, value: "centimetre" },
    { id: 4, value: "milimetre" },
    { id: 5, value: "mile" },
    { id: 6, value: "yard" },
  ];

  const selectConversion = (event) => {
    const selectedId = Number(event.target.dataset.id);
    console.log(selectedId);
    // 条件判断逻辑
  };

  return (
    <select onChange={selectConversion}>
      {lenghtArray.map((localState) => (
        <option key={localState.id} data-id={localState.id}>
          {localState.value}
        </option>
      ))}
    </select>
  )
}

方案3:通过选中索引从数组中取id

利用select的selectedIndex属性拿到选中项的索引,再从lenghtArray里取出对应的id:

export default function unitFunc(){
  const lenghtArray = [
    { id: 1, value: "meter" },
    { id: 2, value: "kilometer" },
    { id: 3, value: "centimetre" },
    { id: 4, value: "milimetre" },
    { id: 5, value: "mile" },
    { id: 6, value: "yard" },
  ];

  const selectConversion = (event) => {
    const index = event.target.selectedIndex;
    const selectedId = lenghtArray[index].id;
    console.log(selectedId);
    // 条件判断逻辑
  };

  return (
    <select onChange={selectConversion}>
      {lenghtArray.map((localState) => (
        <option key={localState.id}>
          {localState.value}
        </option>
      ))}
    </select>
  )
}

这三种方案里,方案1最常用,因为value属性是select元素的标准属性,逻辑更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:10:33