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

ReactJS如何获取动态datalist选中项对应的员工ID

React动态datalist获取选中项员工ID解决方案

以下提供3种不同场景的可行实现方案:

方案1:姓名匹配查找(无需修改现有渲染逻辑)

适合员工姓名无重复的场景,直接通过input返回的姓名在员工数组中匹配对应对象即可,仅需要修改handleChange函数:

const handleChange = (event) => {
  const selectedName = event.target.value;
  // 匹配对应员工对象
  const selectedEmployee = employees.find(emp => emp.name === selectedName);
  if (selectedEmployee) {
    // 可直接获取完整员工对象与ID
    console.log('选中员工ID:', selectedEmployee.id);
  }
};

方案2:value拼接ID+姓名(解决重名问题)

如果存在员工姓名重复的情况,可以将ID与姓名拼接后存入option的value属性,选中后拆分取值即可:
首先修改datalist的option渲染逻辑:

<option 
  key={result.id} 
  value={`${result.id} - ${result.name}`}
>
  {result.name}
</option>

再修改handleChange函数解析取值:

const handleChange = (event) => {
  const selectedValue = event.target.value;
  const [empId, empName] = selectedValue.split(' - ');
  if (empId) {
    console.log('选中员工ID:', empId);
    // 也可通过ID匹配完整员工对象
    const selectedEmployee = employees.find(emp => emp.id === Number(empId));
  }
};

方案3:自定义属性存储ID(输入框仅显示姓名)

如果不想让ID显示在输入框内,可以给option添加自定义data-id属性存储ID,选中后遍历datalist选项匹配取值:
首先修改option渲染逻辑:

<option 
  key={result.id} 
  value={result.name}
  data-id={result.id}
>
  {result.name}
</option>

再修改handleChange函数:

const handleChange = (event) => {
  const selectedName = event.target.value;
  const datalistOpts = document.getElementById('listOfEmployees').options;
  let selectedId = null;
  // 遍历选项匹配对应ID
  for (const opt of datalistOpts) {
    if (opt.value === selectedName) {
      selectedId = opt.dataset.id;
      break;
    }
  }
  if (selectedId) {
    console.log('选中员工ID:', selectedId);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:42:02