繁体   English   中英

在 React Typescript 中,如何为原生 html 元素定义 ...rest 参数的类型?

[英]In React Typescript how to define type for …rest parameter for native html elements?

我正在尝试过滤一些道具,然后将道具的 rest 传递给本机 html 元素,如下所示:

const Placeholder = (
  display: boolean,
  ...rest: Array<React.LabelHTMLAttributes<HTMLLabelElement>>
) => <label {...rest} />

问题是这给了我这个错误:

Type '{ length: number; toString(): string; toLocaleString(): string; pop(): LabelHTMLAttributes<HTMLLabelElement> | undefined; push(...items: LabelHTMLAttributes<HTMLLabelElement>[]): number; ... 28 more ...; flat<U>(this: U[][][][][][][][], depth: 7): U[]; flat<U>(this: U[][][][][][][], depth: 6): U[]; flat<U>(this: U[]...' has no properties in common with type 'DetailedHTMLProps<LabelHTMLAttributes<HTMLLabelElement>, HTMLLabelElement>'.ts(2559)

我将如何为原生 html 元素(如label中的 label)定义...rest参数的类型?

label的类型为: React.DetailedHTMLProps<React.LabelHTMLAttributes<HTMLLabelElement>, HTMLLabelElement>

所以依靠这个,这样的事情应该可以工作:

interface Props
  extends React.DetailedHTMLProps<
    React.LabelHTMLAttributes<HTMLLabelElement>,
    HTMLLabelElement
  > {
  display: boolean;
}

const Placeholder = ({ display, ...rest }: Props) => <label {...rest} />;

const App = () => <Placeholder display htmlFor="form" />;

另外,请注意,由于第一个参数是props被解构为 object (所以...rest是剩余的 props 作为对象),而不是作为数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM