首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React.HTMLProps<HTMLButtonElement>破坏了defaultProps

React.HTMLProps<HTMLButtonElement>破坏了defaultProps
EN

Stack Overflow用户
提问于 2019-02-13 12:22:58
回答 3查看 2.5K关注 0票数 2

我为我的按钮样式组件的PropTypes编写了以下代码

代码语言:javascript
运行
AI代码解释
复制
export type Props = {
  size?: 'small' | 'medium' | 'large',
};

StyledButton.defaultProps = {
  size: 'medium',
};

它工作得很好,但后来我想要包含HTMLButtonElement属性来为我的按钮提供交互性。因此,我添加了以下内容:

代码语言:javascript
运行
AI代码解释
复制
export type Props = React.HTMLProps<HTMLButtonElement> & {
  size?: 'small' | 'medium' | 'large',
};

StyledButton.defaultProps = {
  size: 'medium',
};

然而,这一变化引起了defaultProps的抱怨。这就是我得到的错误。

代码语言:javascript
运行
AI代码解释
复制
Types of property 'size' are incompatible.
    Type 'string' is not assignable to type 'undefined'.ts(2322)

但是,如果我去掉React.HTMLProps,它可以工作,但这不是我想要的。有没有人知道解决这个问题的办法?

提前谢谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-02-13 12:48:28

我认为你必须定义一个新的接口:

代码语言:javascript
运行
AI代码解释
复制
export interface Props extends React.HTMLProps<HTMLButtonElement> {
  size?: 'small' | 'medium' | 'large',
};

问题是React.HTMLProps,或者更确切地说,它的超级接口HTMLAttributes已经包含了一个size属性,其定义如下:

代码语言:javascript
运行
AI代码解释
复制
size?: number;

因此,您必须重命名您的属性。

票数 5
EN

Stack Overflow用户

发布于 2019-04-10 13:55:02

我还发现,如果您想为size属性设置自定义值,简单地扩展React.HTMLProps<HTMLButtonElement>是不起作用的。这里有一个解决这个问题的方法。我们将需要来自utility-types包(https://github.com/piotrwitek/utility-types#omitt-k)的名为Omit的小助手。

并像这样使用它:

代码语言:javascript
运行
AI代码解释
复制
import { Omit } from 'utility-types';

type BaseButtonProps = Omit<React.HTMLProps<HTMLButtonElement>, 'size'>;

interface ButtonProps {
  size?: 'lg' | 'sm';
}

const Button: React.FC<ButtonProps & BaseButtonProps> = ({ size }) => {
  // size is now 'lg', 'sm' or undefined
};
票数 1
EN

Stack Overflow用户

发布于 2019-02-13 13:07:29

因此,在我查看站点https://medium.com/@martin_hotell/react-typescript-and-defaultprops-dilemma-ca7f81c661c7时,请尝试以下内容

代码语言:javascript
运行
AI代码解释
复制
type Props = Partial<DefaultProps>;

type DefaultProps = Readonly<typeof defaultProps>;

const defaultProps = {
  size: 'small' as 'small' | 'medium' | 'large';
};

export YourClass extends React.Component<Props> { }

这可能是解决问题的最简单、最容易的方法,尽管如果这不起作用,还有其他方法可能会有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54670121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档