Jas*_*ugh 5 typescript reactjs material-ui
我有一个这样的常数:
const Reference = [
{ label: "RF-100", year: "Test" },
{ label: "RF-200", year: "Test2" },
{ label: "RF-300", year: "Test3" },
];
Run Code Online (Sandbox Code Playgroud)
我在 MUI 中有自动完成功能,如下所示:
export const Auto: React.FC = () => {
return (
<Autocomplete
id="Combox-demo"
options={Reference}
//getOptionLabel={(option) => `${option.name}`}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" prefix="RF" />}
/>
);
};
Run Code Online (Sandbox Code Playgroud)
我试图让我的 getOptionLabel 显示标签 - 年,所以它将是 RF-100 - 测试(作为示例)
当我使用
getOptionLabel={(option) => `${option.label}`}
Run Code Online (Sandbox Code Playgroud)
我明白了
类型“string | ”上不存在属性“label” { 标签:字符串;年:字符串;}'。类型“string”上不存在属性“label”
大家有什么想法吗?
Lin*_*ste 11
您在 TypeScript 错误中看到option
回调中的 可能是一个选项对象或只是一个string
:
string | { label: string; year: string; }
Run Code Online (Sandbox Code Playgroud)
其原因是由于自动完成的“自由独奏”模式,用户可以输入任何任意文本,而不仅限于提供的选项。
该道具的文档getOptionLabel
说:
如果在自由独奏模式下使用,它必须接受选项类型和字符串。
对于如何继续,您有两种选择。
string
. 如果不是,则它必须具有类型{ label: string; year: string; }
。这涉及到运行时的检查,但它更安全——如果您要启用自由独奏模式,那么什么都不会破坏,因为您正在正确处理string
和object
值。getOptionLabel={(option) => typeof option === "string" ? option : option.label}
Run Code Online (Sandbox Code Playgroud)
freeSolo
prop,那么您可以进行类型断言。这本质上是在告诉 TypeScript “相信我”。getOptionLabel={(option) => (option as { label: string }).label}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1880 次 |
最近记录: |