如何禁用 PrimeReact ListBox 中的列表项之一?

How to disable one of the list item in PrimeReact ListBox?

对于 PrimeReact ListBox 实现:

const cities = [
    {name: 'New York', code: 'NY'},
    {name: 'Rome', code: 'RM'},
    {name: 'London', code: 'LDN'},
    {name: 'Istanbul', code: 'IST'},
    {name: 'Paris', code: 'PRS'}
];

<ListBox 
  optionLabel="name" 
  optionValue="code" 
  value={city} 
  options={cities} 
  onChange={(e) => setCity(e.value)} 
/>

我得到了包含列表项的正确面板。但是如何禁用列表项,比如 New York 需要禁用被选中,如何实现?

解决方案是将 属性 的名称传递给选项的禁用状态,如下所示:

const cities = [
  { name: 'New York', code: 'NY', disabled: true },
  { name: 'Rome', code: 'RM' },
  { name: 'London', code: 'LDN' },
  { name: 'Istanbul', code: 'IST' },
  { name: 'Paris', code: 'PRS' },
];

<ListBox
  optionLabel="name"
  optionValue="code"
  value={city}
  options={cities}
  optionDisabled="disabled"
  onChange={(e) => setCity(e.value)}
/>

或者将决定禁用哪一个的函数,其中选项是列表中的一项,同时迭代列表

const cities = [
  { name: 'New York', code: 'NY' },
  { name: 'Rome', code: 'RM' },
  { name: 'London', code: 'LDN' },
  { name: 'Istanbul', code: 'IST' },
  { name: 'Paris', code: 'PRS' },
];

<ListBox
  optionLabel="name"
  optionValue="code"
  value={city}
  options={cities}
  optionDisabled={(option) => option.name === 'New York"}
  onChange={(e) => setCity(e.value)}
/>