typescript React.HTMLProps〈>和React.HTMLAttributes之间的区别是什么< T>?

91zkwejq  于 2022-12-24  发布在  TypeScript
关注(0)|答案(2)|浏览(188)

我正在尝试为我的组件定义一个props接口,并希望它包括所有公共属性。
但发现有两个不同的接口我可以扩展
interface MyProps extend React.HTMLProps<HTMLElement>interface MyProps extend React.HTMLAttributes<HTMLElement>
有什么区别?我应该用哪一个?看起来HTMLProps包括HTMLAttributes,这是否意味着HTMLProps应该是一个更好的候选者?

hujrc8aj

hujrc8aj1#

HTMLProps包含的内容比HTMLAttributes多,比如ref等等。
我过去做过以下几件事:

export interface PrimitiveProps extends React.HTMLProps<HTMLDivElement> { };

对我来说一切都很顺利🌹

oxf4rvwz

oxf4rvwz2#

现在您应该使用ComponentPropsWithoutRefComponentPropsWithRef

export interface PrimitiveProps extends React.ComponentPropsWithoutRef<'div'> { };

React.HTMLPropsReact.HTMLAttributes实际上为某些属性推断了错误的类型,或者未包含所有可能的值。
HTMLProps示例错误:

export interface ButtonProps extends React.HTMLProps<HTMLButtonElement> {}
export function Button(props: ButtonProps) {
  // ERROR: Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.
  return <button {...props} />;
}

HTMLAttributes示例错误:

export interface ButtonProps extends React.HTMLAttributes<HTMLButtonElement> {}
export function Button(props: ButtonProps) {
  return <button {...props} />;
}

// Error: Property 'type' does not exist on type 'IntrinsicAttributes & ButtonProps'.
<Button type="button">Test</Button>

要了解更多信息,您可以阅读备忘单,部分“为什么不是组件属性或内在元素或[元素]HTMLAttributes或HTMLProps或HTMLAttributes?”

相关问题