在 React 和 TypeScript 中扩展 HTML 元素,同时保留 props
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40731352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extending HTML elements in React and TypeScript while preserving props
提问by Josh
I just can't wrap my head around this I guess, I've tried probably half a dozen times and always resort to any
... Is there a legitimate way to start with an HTML element, wrap that in a component, and wrap that in another component such that the HTML props pass through everything? Essentially customizing the HTML element? For example, something like:
我想我只是无法解决这个问题,我已经尝试了大约六次并且总是求助于any
......是否有一种合法的方法可以从 HTML 元素开始,将其包装在组件中,然后将其包装起来在另一个组件中,以便 HTML 道具通过所有内容?本质上是自定义 HTML 元素?例如,类似于:
interface MyButtonProps extends React.HTMLProps<HTMLButtonElement> {}
class MyButton extends React.Component<MyButtonProps, {}> {
render() {
return <button/>;
}
}
interface MyAwesomeButtonProps extends MyButtonProps {}
class MyAwesomeButton extends React.Component<MyAwesomeButtonProps, {}> {
render() {
return <MyButton/>;
}
}
Usage:
用法:
<MyAwesomeButton onClick={...}/>
Whenever I attempt this sort of composition, I get an error similar to:
每当我尝试这种组合时,都会收到类似于以下内容的错误:
Property 'ref' of foo is not assignable to target property.
foo 的属性“ref”不可分配给目标属性。
回答by Jordan Upham
You can change the definition of your component to allow the react html button props
您可以更改组件的定义以允许响应 html 按钮道具
class MyButton extends React.Component<MyButtonProps & React.HTMLProps<HTMLButtonElement>, {}> {
render() {
return <button {...this.props}/>;
}
}
That will tell the typescript compiler that you want to enter the button props along with 'MyButtonProps'
这将告诉打字稿编译器您要输入按钮道具和“MyButtonProps”
回答by EimerReis
Seems Like the above answer is outdated.
似乎上面的答案已经过时了。
In my case I'm wrapping a styled component with a functional component, but still want to expose regular HTML button properties.
在我的例子中,我用一个功能组件包装了一个样式组件,但仍然想公开常规的 HTML 按钮属性。
export const Button: React.FC<ButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>> = ({ children, icon, ...props}) => (
<StyledButton { ...props}>
{ icon && (<i className = "material-icons" >{icon}< /i>)}
{children}
</StyledButton>);