我试图通过对象解构来提取
key
属性,但 TypeScript 告诉我 Property 'key' does not exist on type 'HTMLAttributes<HTMLLIElement>
尽管事实上,当我
console.log(props)
时,我得到以下信息:
{
"key": "Miami, FL, USA",
"tabIndex": -1,
"role": "option",
"id": "location-input-option-0",
"data-option-index": 0,
"aria-disabled": false,
"aria-selected": false,
"className": "MuiAutocomplete-option"
}
renderOption={(props, option) => {
console.log("renderOption props:", props);
const { key } = props;
const matches =
option.structured_formatting.main_text_matched_substrings || [];
const parts = parse(
option.structured_formatting.main_text,
matches.map((match: any) => [
match.offset,
match.offset + match.length,
]),
);
return (
<li {...props}>
<Grid container alignItems="center">
<Grid item sx={{ display: "flex", width: 44 }}>
<LocationOnIcon sx={{ color: "text.secondary" }} />
</Grid>
<Grid
item
sx={{ width: "calc(100% - 44px)", wordWrap: "break-word" }}
>
{parts.map((part, index) => (
<Box
key={index}
component="span"
sx={{ fontWeight: part.highlight ? "bold" : "regular" }}
>
{part.text}
</Box>
))}
<Typography variant="body2" color="text.secondary">
{option.structured_formatting.secondary_text}
</Typography>
</Grid>
</Grid>
</li>
);
}
这只是因为属性
key
以及 data-option-index
不属于 HTMLAttributes<HTMLLIElement>
类型。要访问这些类型安全的附加属性,您需要将它们添加到类型定义中。
props: HTMLAttributes<HTMLLIElement> & {key: string, "data-option-index": number}
在你的情况下,我会使用类似的东西:
type RenderOptionProps = {
props: HTMLAttributes<HTMLLIElement> & {key: string, "data-option-index": number};
option: any; // better choose something else
}
const renderOption= ({props, option}: RenderOptionProps) => {...}