如何扩展 React 类型以支持 html 属性作为 props [英] How extend React types to support html attributes as props
本文介绍了如何扩展 React 类型以支持 html 属性作为 props的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个带有自定义 props 和 html 属性 props 的组件,应该如何创建这样一个组件的界面?理想情况下,界面还可以处理特定于 react 的 html 道具,例如使用 className
而不是 class
.
Given a component that takes custom props as well as html attribute props, how should the interface for such a component be created? Ideally, the interface would also handle react-specific html props such as using className
instead of class
.
我试图为其找到正确界面的使用示例:
Usage example for which I'm trying to find the right interface:
<MyComponent customProp='value' style={{textAlign: 'center'}} />
推荐答案
interface IMyComponentProps extends React.HTMLAttributes<HTMLElement> {
customProp: string;
}
更新:@ddek 提到了交叉点&
.
UPD:
@ddek mentioned intersections &
.
我想就该方法的以下问题向您发出警告.
I would like to warn you about the following issue with that approach.
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;
}
这篇关于如何扩展 React 类型以支持 html 属性作为 props的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文