React-Select isMulti模式下如何根据条件禁用特定选项
Solution for Disabling Specific Option in react-select isMulti Component
Hey there! To disable the option that matches your systemDetails.SYSTEMID in the multi-select component, you just need to add the isDisabled property to the corresponding option object when mapping your dataSystems array. React-select automatically respects this property and disables the option for selection.
Here's your modified code with the fix:
import Select from 'react-select' const Systems = () => { const [dataSystems, setdataSystems] = useState([]) const [systemDetails, setsystemDetails] = useState({ SYSTEMID: 1, ...... }) const getSystems = async() => { await axios.get('/API') .then(response => { setdataSystems(response.data) }) } const [multiSelected, setmultiSelected] = useState(); var handleMultiSelect = (e) => { setmultiSelected(Array.isArray(e)?e.map(x=> x.value):[]); } const bodyInsertDepSystem = ( // ... your other JSX content <Select isMulti options={dataSystems.map(e => ({ label: e.SYSTEMALIAS, value: e.SYSTEMID, // Add this line to disable the matching option isDisabled: e.SYSTEMID === systemDetails.SYSTEMID }))} onChange={handleMultiSelect} /> ) }
How this works:
- When mapping each system in
dataSystems, we check if itsSYSTEMIDis equal tosystemDetails.SYSTEMID. - If they match, we set
isDisabled: truefor that option. React-select will gray out this option and prevent users from selecting it, which perfectly fits your edit scenario where you don't want to associate a system with itself.
If you ever wanted to remove the option entirely instead of just disabling it, you could add a filter before the map:
options={dataSystems .filter(e => e.SYSTEMID !== systemDetails.SYSTEMID) .map(e => ({ label: e.SYSTEMALIAS, value: e.SYSTEMID })) }
But disabling is probably better here since it keeps the user aware that this system exists but can't be selected for this operation.
内容的提问来源于stack exchange,提问作者JayDee
相关产品推荐
相关产品推荐

