[英]Spreading props on a React component with Typescript
Typescript + React 的新手,我正在嘗試在ListItem
的根節點上傳播道具。 例如,我想為這個組件允許data-*
和aria-*
屬性。 下面是代表我遇到的問題的示例組件。
import { forwardRef, HTMLAttributes } from 'react';
interface ListItemProps extends HTMLAttributes<HTMLElement> {
disabled?: boolean;
active?: boolean;
href?: string;
}
const ListItem = forwardRef<HTMLLIElement, ListItemProps>((props, ref) => {
const {
active,
disabled,
className,
style,
children,
...other
} = props;
return (
<li // throws error
ref={ref}
style={style}
{...other}
>{children}</li>
);
});
export default ListItem;
我收到此打字稿錯誤:
TS2322: Type '{ children: Element; href?: string | undefined; defaultChecked?: boolean | undefined; defaultValue?: string | string[] | undefined; suppressContentEditableWarning?: boolean | undefined; ... 249 more ...; className: string; }' is not assignable to type 'DetailedHTMLProps<LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>'.
Type '{ children: Element; href?: string | undefined; defaultChecked?: boolean | undefined; defaultValue?: string | string[] | undefined; suppressContentEditableWarning?: boolean | undefined; ... 249 more ...; className: string; }' is not assignable to type 'LiHTMLAttributes<HTMLLIElement>'.
Types of property 'inputMode' are incompatible.
Type 'string | undefined' is not assignable to type '"text" | "none" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined'.
Type 'string' is not assignable to type '"text" | "none" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined'.
這是因為您將變量用作inputMode
作為string
(通過注釋或推理)。
使用注釋React.HTMLAttributes<HTMLLIElement>['inputMode']
(使用查找類型)。
固定代碼:
import * as React from 'react';
import { forwardRef, HTMLAttributes } from 'react';
interface ListItemProps extends HTMLAttributes<HTMLElement> {
disabled?: boolean;
active?: boolean;
href?: string;
}
const ListItem = forwardRef<HTMLLIElement, ListItemProps>((props, ref) => {
const {
active,
disabled,
className,
style,
children,
...other
} = props;
return (
<li // throws error
ref={ref}
style={style}
{...other}
>{children}</li>
);
});
// Issue with inputMode
let asString = "text";
const error = <ListItem inputMode={asString}/>;
// Fix
let correctType:React.HTMLAttributes<HTMLLIElement>['inputMode'] = "text";
const ok = <ListItem inputMode={correctType}/>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.