DetailedHTMLProps和HTMLAttributes有什么区别?

12

假设我有一个组件接口,应该扩展标准<div>元素的接口。写法上有什么区别:

interface ComponentProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> { ... }

相对于这个:

interface ComponentProps extends React.HTMLAttributes<HTMLDivElement> { ... }
1个回答

24

让我们创建ComponentProps类型:

interface ComponentProps1 extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {}

interface ComponentProps2 extends React.HTMLAttributes<HTMLDivElement> {}

那么我们可以很容易地检查它们之间的差异:

type Dif = Omit<ComponentProps1, keyof ComponentProps2>;

Dif 类型是:

type Dif = {
    ref?: LegacyRef<HTMLDivElement>;
    key?: string | number;
}

2
那么 DetailedHTMLProps 只包括 keyref 吗?在 React 中,这些不是自动设置在类和函数组件上吗?我什么时候需要扩展 DetailedHTMLProps 呢? - o01
1
key and ref are defined on react class and functional component but at the same time, they do not defined HtmlAttributes. It is reasonable to use this type for all JSX.IntrinsicElements. I think I would not extend DetailedHTMLProps as it should be used as a wrapper for your HtmlAttributes<Element> - Marcin
@Marcin,谢谢你的精彩回答。我还有一个问题,ref和key有什么用?为什么我要使用DetailedHTMLProps而不只是HtmlAttributes? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接