如何使用 Typescript 在 React 中导入标准 DOM 元素道具

How to import standard DOM element props in React with Typescript

我在 TypeScript 中创建 React 组件并键入提示道具,如下所示:

export interface ExampleProps {
  someProp: string,
  anotherProp: React.ReactNode
}

export default function Example({
  someProp, 
  ...props
}: ExampleProps) {
  return (
    <div {...props}>...</div>
  );
}

我还想传递标准 React/HTML 道具,例如 classNamechildrenstyleidtitlelang,等等......而不必明确地写出所有这些。所以我可以做类似的事情:

<Example className="some-class" someProp="value" anotherProp={<div></div>}>Content</Example>

我原以为应该可以为此扩展一个接口:

export interface ExampleProps extends PropsWithChildren {
  someProp: string,
  anotherProp: React.ReactNode
}

但这抱怨:Generic type 'PropsWithChildren' requires 1 type argument(s)

export interface ExampleProps extends PropsWithChildren<typeof Example> {
  someProp: string,
  anotherProp: React.ReactNode
}

但是这个抱怨,Type { children: string; className: string; someProp: string, anotherProp: Element }' is not assignable to type 'IntrinsicAttributes & SlotsProps

然后我尝试了:

export interface ExampleProps extends PropsWithChildren<{}> {
  someProp: string,
  anotherProp: React.ReactNode
}

但这会引起抱怨,Property 'className' does not exist on type 'IntrinsicAttributes & SlotsProps',因为显然 PropsWithChildren 包含的所有内容都是子项。

所以我也尝试用 ComponentPropsElementType 替换 PropsWithChildren 但这也没有帮助。

React 不维护适用于所有元素的标准属性列表吗?

您确实可以而且应该使用 extends:

export interface ExampleProps extends React.HTMLAttributes<HTMLDivElement> {
    someProp: string;
}

export default function Example({ someProp, ...restProps }: ExampleProps) {
    return <div {...restProps} />;
}

根据您的 IDE,您实际上可以单击 or hover 您想要的元素并阅读它的类型。