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

ary*_*ing 7 typescript reactjs

给定一个带有自定义属性和html属性属性的组件,应如何为该组件创建接口?理想情况下,该接口还可以处理特定于React的html道具,例如using className代替class

我正在尝试找到正确接口的用法示例:

<MyComponent customProp='value' style={{textAlign: 'center'}}  />
Run Code Online (Sandbox Code Playgroud)

Yoz*_*ozi 15

interface IMyComponentProps extends React.HTMLAttributes<HTMLElement> {
  customProp: string;
}
Run Code Online (Sandbox Code Playgroud)


dde*_*dek 6

Yozi 是对的,但还有另一种方法,它演示了打字稿(和通用 FP)功能,如果您来自 C# 或 Java 之类的语言,您可能不熟悉该功能。

interface MyCustomProps {
    customProp: string;
}

const MyComponent = (props: MyCustomProps & React.HTMLAttributes<...>) 
    => (...)
Run Code Online (Sandbox Code Playgroud)

&在打字稿中,类型声明中的an指的是交集类型您可以在 typescript 文档中阅读更多内容。该对象现在结合了和 HTML 属性props的属性。MyCustomProps(还值得学习有区别的联合或or类型,它们用 表示|。我发现它们比交集更有用)。

如果你想清理你的方法签名,你可以声明类型如下:

interface MyCustomProps {...}
type ComponentProps = MyCustomProps & React.HTMLAtributes<...>;
Run Code Online (Sandbox Code Playgroud)

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