首页 > 解决方案 > react-select:在onChange期间从另一个Select清除所选值

问题描述

我的反应功能组件中有 2 个选择元素,如下所示:

<Select
  options={areaTimeSlots}
  onChange={ (selectedTimeSlotLabel) => handleTimeSlot (selectedTimeSlotLabel) }
  placeholder="Select a delivery slot"
/>

<Select options={areaData} onChange={(value) => handleSelectedArea(value)}  />

onChange如果从 select-2 (handleSelectedArea) 触发,我想从 areaTimeSlots (select-1) 中清除所选选项。

我尝试使用反应钩子和 ref 如下所示,但两者都不起作用

const [selectedTimeSlotLabel, setTimeSlotLabel] = useState(null);
const handleSelectedArea = async (e: any) => {
  setTimeSlotLabel(null);
}
 
<Select
  options={areaTimeSlots}
  isClearable={true}
  onChange={ (selectedTimeSlotLabel) => handleTimeSlot (selectedTimeSlotLabel) }
  value={selectedTimeSlotLabel}  placeholder="Select a delivery slot"
/>

标签: reactjsreact-hooksreact-select

解决方案


您可以控制第一个的值Select并在更改第二个时将其重置:

const [value, setValue] = React.useState(null);

return (
  <>
    <Select options={options1} value={value} onChange={setValue} />
    <Select options={options2} onChange={() => setValue(null)} />
  </>
);

Codesandbox 演示


推荐阅读