PrimeReact Autocomplete:选中后禁用对应选项的实现方案
如何在PrimeReact的Autocomplete组件中禁用已选中的选项
需求:选中某个选项(比如“阿富汗”)后,该选项需立即在下拉列表中变为禁用状态,无法再次选择。
实现步骤:
- 标记已选中的选项为禁用
在生成过滤后的选项列表时,给每个选项添加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); };
- 自定义选项模板,添加禁用样式
修改itemTemplate,根据disabled属性给选项添加禁用样式,让用户直观识别不可选状态:
const itemTemplate = (item) => { return ( <div className={`country-item ${item.disabled ? 'disabled-item' : ''}`}> <div>{item.name}</div> </div> ); };
- 添加禁用状态的CSS样式
为禁用选项添加视觉区分样式:
.disabled-item { color: #cccccc; cursor: not-allowed; }
原理说明:
PrimeReact的Autocomplete组件会自动识别选项对象中的disabled属性,当该属性为true时,组件会阻止用户选中该选项。配合自定义样式,就能实现选中后选项立即禁用的效果。
内容的提问来源于stack exchange,提问作者Darkpsinight_2
相关产品推荐
相关产品推荐

