我已经尝试查看SO中的几个答案,但它们都在普通的javascript中,根本不考虑Typescript,Javascript在没有类型的情况下工作正常,但TSX有点不同,我才刚刚开始反应。我正在使用
react-select
组件进行选择。
Option/IOption类/接口
export interface IOption {
value: string | null;
label: string;
icon?: string;
}
export class Option implements IOption {
public value:string | null;
public label: string;
public icon?: string | undefined;
constructor(){
this.value = null;
this.label = "";
}
}
AlergiaForm.Component.tsx
const AlergiaForm = () => {
//For sake of simplicity, ignoring rest of the code
const option = new Option();
option.value = "5"; //hardcoding to test react-select clear value or selection
const[comprador, setComprador] = useState(option);
//When dropdown changes, it detects the value and save it to another state
//This is working fine to grab the value...
const handleDropDownChange = (selectedOption: SingleValue<IOption>, name: string):void
=> {
const { value } = {...selectedOption};
setFormFields({...formFields, [name] : value});
}
//Changing the "comprador" option to new Option() so it "clears" the value, but not working...
const resetFields = () => {
setComprador(new Option());
}
//Populating options as IOption that react-select is using
const options = [
{ value: '1', label: 'First value' },
{ value: '5', label: 'This should be selected, but no' },
{ value: '6', label: 'Other stuff' }
] as IOption[];
return(
<>
{/*The value={comprador} is not complaining, but the dropdown does not populate any value or allows to make it selected (it grabs the value in the handleDropDownChange(), but is not displaying it correctly) */}
<Select onChange={(selectedOption) => handleDropDownChange(selectedOption, "fieldName")} options={options} value={comprador} />
<button onClick={resetFields}>Reset</button>
</>
);
}
export default AlergiaForm;
JS 中的示例,他们说它有效,但对我来说不起作用: 如何以编程方式清除/重置 React-Select?
发生的事情的结果(反应选择应该有一个文字说“选择...”,当我选择一个选项时,它仍然是空白的:
“工作”行为示例 示例
您需要像文档中一样将默认状态设置为 null。
还需要将类型添加到状态以修复打字稿无法分配给 null
useState<SingleValue<IOption> | null>(null)