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

时间:2018-05-31 15:09:44

标签: reactjs typescript

鉴于一个组件需要自定义道具以及html属性道具,如何创建这样一个组件的接口?理想情况下,界面还可以处理特定于反应的html道具,例如使用className代替class

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

<MyComponent customProp='value' style={{textAlign: 'center'}}  />

2 个答案:

答案 0 :(得分:3)

interface IMyComponentProps extends React.HTMLAttributes<HTMLElement> {
  customProp: string;
}

答案 1 :(得分:3)

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

interface MyCustomProps {
    customProp: string;
}

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

在打字稿中,类型声明中的&指的是交叉点类型You can read more in the typescript docsprops对象现在结合了MyCustomProps的属性和HTML属性。 (值得一提的是使用or表示的区别联合或|类型。我发现它们比交集更有用。)

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

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

但是,这种表示法现在已经失去了前面两种方法的简洁性-extends语法和&表示法。