如何扩展 React 类型以支持 html 属性作为props?

IT技术 reactjs typescript
2021-05-07 11:27:41

给定一个接受自定义props以及 html 属性props的组件,应该如何创建这样一个组件的界面?理想情况下,界面还将处理特定于 react 的 html props,例如使用className代替class.

这是我试图为其找到正确界面的使用示例:

<MyComponent customProp='value' style={{textAlign: 'center'}}  />
2个回答
interface IMyComponentProps extends React.HTMLAttributes<HTMLElement> {
  customProp: string;
}

UPD:@ddek 提到了交叉点&

我想警告您有关该方法的以下问题。


interface A {
  onClick: () => void;
}

interface B {
  onClick: (event: React.MouseEvent<HTMLElement>) => void;
}

// Typescript does not complain. This is not good
type AB = A & B;
const a: AB = {
  onClick: () => {}
};


// TS2320: Interface 'AB2' cannot simultaneously extend types 'A' and 'B'.
// Named property 'onClick' of types 'A' and 'B' are not identical.

interface AB2 extends A, B {

}

// TS2430: Interface 'AC' incorrectly extends interface 'A'.
//   Types of property 'onClick' are incompatible.  
//   Type '(event: MouseEvent<HTMLElement, MouseEvent>) => void' is not
// assignable to type '() => void'.
interface AC extends A {
  onClick: (event: React.MouseEvent<HTMLElement>) => void;
}

Yozi 是对的,但还有另一种方式,它演示了一个typescript(和一般 FP)功能,如果您来自 C# 或 Java 之类的东西,您可能不熟悉该功能。

interface MyCustomProps {
    customProp: string;
}

const MyComponent = (props: MyCustomProps & React.HTMLAttributes<...>) 
    => (...)

在typescript中,&类型声明中的 an 指的是一个交集类型您可以在typescript文档中阅读更多内容props对象现在结合了MyCustomProps和 HTML 属性的属性。(也值得学习区分联合或or类型,用 表示|。我发现这些比交叉更有用)。

如果要清理方法签名,可以按如下方式声明类型:

interface MyCustomProps {...}
type ComponentProps = MyCustomProps & React.HTMLAtributes<...>;

然而,这种表示法现在已经失去了之前两种方法的简洁性——extends语法和&表示法。