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

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 its SYSTEMID is equal to systemDetails.SYSTEMID.
  • If they match, we set isDisabled: true for 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:08:10