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

react-select使用自定义option时选择失效、onChange无法取值如何解决?

你的代码存在两处核心错误:

  1. value属性使用错误
    react-select的value属性需要传入当前选中的实际值,与getOptionValue的返回值格式对齐,而非取值函数。你传入了箭头函数导致组件无法匹配选中的选项,自然无法响应点击选中操作。

  2. onChange回调传参错误
    react-select的onChange触发时会自动将当前选中的option对象作为参数传入绑定的处理函数,你额外嵌套的匿名函数把(option) => option.phaseText这个函数本身作为参数传给了HandelChange,所以打印结果是函数的字符串形式。

修正后的完整代码如下:

import { useState } from 'react';
import Select from 'react-select';

// 此处保留你之前定义的styles变量即可

const YourComponent = () => {
  // 新增选中值状态,用于绑定value属性
  const [selectedPhase, setSelectedPhase] = useState('');
  const HandelChange = (selectedOption) => {
    // 直接从入参拿到选中的option对象,按需取值即可
    console.log(selectedOption.phaseText);
    setSelectedPhase(selectedOption.phaseText);
  };
  const [dataPhase, setDataPhase] = useState([
    { phaseID: 1, phaseText: "Item 1" },
    { phaseID: 2, phaseText: "Item 2" },
    { phaseID: 3, phaseText: "Item 3" },
    { phaseID: 4, phaseText: "Item 4" },
    { phaseID: 5, phaseText: "Item 5" },
  ]);

  return (
    <Select
      isSearchable
      options={dataPhase}
      getOptionLabel={(option) => option.phaseText}
      getOptionValue={(option) => option.phaseText}
      className="diMultiSelect"
      classNamePrefix="diSelect"
      styles={styles}
      maxMenuHeight={150}
      // 传入实际选中值,和getOptionValue返回值格式对齐
      value={selectedPhase}
      // 直接绑定处理函数,无需额外套匿名函数
      onChange={HandelChange}
    />
  )
}

补充说明:

  • 如果需要设置默认选中项,初始化selectedPhase时直接赋值对应phaseText即可,例如useState("Item 2")
  • 如果你后续需要存选中的完整option对象,只需把getOptionValue改为返回phaseID,selectedPhase初始化为空对象,setSelectedPhase直接存selectedOption,value绑定selectedPhase即可,两者格式对齐就能正常工作。

内容的提问来源于stack exchange,提问作者Sikandar Ali Chishty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:54:03