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

PrimeReact Autocomplete:选中后禁用对应选项的实现方案

如何在PrimeReact的Autocomplete组件中禁用已选中的选项

需求:选中某个选项(比如“阿富汗”)后,该选项需立即在下拉列表中变为禁用状态,无法再次选择。

实现步骤:

  1. 标记已选中的选项为禁用
    在生成过滤后的选项列表时,给每个选项添加disabled属性,判断当前选项是否和已选中项一致:
const searchCountry = (event) => {
  setTimeout(() => {
    let _filteredCountries;
    if (!event.query.trim().length) {
      _filteredCountries = [...countries].map(country => ({
        ...country,
        // 对比已选中项,标记禁用状态
        disabled: selectedCountry2 && country.name === selectedCountry2.name
      }));
    } else {
      _filteredCountries = countries.filter((country) => {
        return country.name
          .toLowerCase()
          .startsWith(event.query.toLowerCase());
      }).map(country => ({
        ...country,
        disabled: selectedCountry2 && country.name === selectedCountry2.name
      }));
    }

    setFilteredCountries(_filteredCountries);
  }, 250);
};
  1. 自定义选项模板,添加禁用样式
    修改itemTemplate,根据disabled属性给选项添加禁用样式,让用户直观识别不可选状态:
const itemTemplate = (item) => {
  return (
    <div className={`country-item ${item.disabled ? 'disabled-item' : ''}`}>
      <div>{item.name}</div>
    </div>
  );
};
  1. 添加禁用状态的CSS样式
    为禁用选项添加视觉区分样式:
.disabled-item {
  color: #cccccc;
  cursor: not-allowed;
}

原理说明:

PrimeReact的Autocomplete组件会自动识别选项对象中的disabled属性,当该属性为true时,组件会阻止用户选中该选项。配合自定义样式,就能实现选中后选项立即禁用的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:15:41