[英]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.