gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:53:43 24 4
gpt4 key购买 nike

我正在尝试过滤一些 props,然后将其余的 props 传递给原生 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)

如何为 Typescript/React 中的 label 等原生 html 元素定义 ...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被解构为一个对象(因此 ...rest 是作为对象的剩余 props),而不是作为数组。

关于javascript - 在 React Typescript 中,如何定义原生 html 元素的 ...rest 参数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58087224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com