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

如何让react-select组件在onChange时更新选中显示状态?

解决react-select选中后不显示选中内容的问题

你的问题核心是react-select的value属性要求传入完整的选项对象,但你当前把country状态存成了单独的字符串值(比如"Afghanistan"),组件无法匹配到对应的选项条目,所以选中后不会显示内容。

修复步骤:

  1. 调整状态存储格式:把country从存字符串改成存整个选项对象
  2. 修正选中判断逻辑:让getOptionSelected正确对比选项和选中对象的value值
  3. 补全缺失的useState导入(原代码里漏了,必须加上)

修改后的完整代码:

import countries from "../utils/COUNTRIES.json";
import Select from "react-select";
import { useState } from "react";

const EventsPage = () => {
  // 初始值设为null,对应未选中状态
  const [country, setCountry] = useState(null);

  const onCountryChange = (selectedOption) => {
    // 直接存储选中的完整选项对象
    setCountry(selectedOption);
  };

  return (
    <Layout>
      <Select
        name="countries"
        id="countries"
        placeholder="Select a country"
        options={countries}
        onChange={onCountryChange}
        value={country}
        getOptionLabel={(option) => option.value}
        // 正确判断当前选项是否为选中项
        getOptionSelected={(option, selected) => option.value === selected.value}        
      />
    </Layout>
  );
};

export default EventsPage;

额外说明:

如果提交表单时只需要国家名称的字符串值,在提交逻辑里取country?.value即可,完全不影响原有的表单提交功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:45:27