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

如何在CreatableSelect中实时获取输入内容的当前长度?

解决方案

问题出在CreatableSelect的onChange回调仅在用户选择已有选项或按下回车创建新选项时触发,无法捕获输入过程中的实时文本。要实现实时更新长度,你需要用到组件提供的onInputChange属性:

修改后的代码示例

import CreatableSelect from 'react-select/creatable';

// 假设你已定义goalOptions和相关状态
const [goal, setGoal] = useState(null);
const [inputText, setInputText] = useState('');

return (
  <>
    <CreatableSelect
      value={goal}
      options={goalOptions}
      onChange={(selectedOption) => {
        setGoal(selectedOption);
        // 选择选项后清空输入文本状态,同步输入框表现
        setInputText('');
      }}
      onInputChange={(newInputValue) => setInputText(newInputValue)}
      placeholder="Select... or type your own!"
    />
    <div>{inputText.length}</div>
  </>
);

原理说明

  • onInputChange会在用户输入每一个字符时实时触发,回调参数就是当前输入框内的文本内容。
  • 通过维护inputText状态存储实时输入值,就能在下方div里实时渲染其长度。
  • 当用户选择已有选项或创建新选项时,通过onChange清空inputText,保证长度显示和输入框状态一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:01:14