在保留道具的同时在React和TypeScript中扩展HTML元素 [英] Extending HTML elements in React and TypeScript while preserving props

查看:114
本文介绍了在保留道具的同时在React和TypeScript中扩展HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我无法解决这个问题,我已经尝试了六次,并且总是使用any ...是否有以HTML元素开头的合法方法,将其包装一个组件,然后将其包装在另一个组件中,以使HTML道具穿过所有内容?本质上是自定义HTML元素?例如,类似:

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:

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/>;
    }
}

用法:

<MyAwesomeButton onClick={...}/>

每当尝试这种合成时,都会出现类似以下错误:

Whenever I attempt this sort of composition, I get an error similar to:

foo的属性'ref'不能分配给目标属性.

Property 'ref' of foo is not assignable to target property.

推荐答案

您可以更改组件的定义以允许使用html按钮props

You can change the definition of your component to allow the react html button props

class MyButton extends React.Component<MyButtonProps & React.HTMLProps<HTMLButtonElement>, {}> {
    render() {
        return <button {...this.props}/>;
    }
}

这将告诉打字稿编译器您想与'MyButtonProps'一起输入按钮道具

That will tell the typescript compiler that you want to enter the button props along with 'MyButtonProps'

这篇关于在保留道具的同时在React和TypeScript中扩展HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆