React.HTMLProps 打破defaultProps

问题描述 投票:0回答:3

我有以下代码用于我的按钮样式组件的PropTypes

export type Props = {
  size?: 'small' | 'medium' | 'large',
};

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

它工作正常,但后来我想包含HTMLButtonElement道具,以提供我的按钮的交互性。因此我补充说:

export type Props = React.HTMLProps<HTMLButtonElement> & {
  size?: 'small' | 'medium' | 'large',
};

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

但是,这种变化使defaultProps抱怨。这是错误,我得到了。

Types of property 'size' are incompatible.
    Type 'string' is not assignable to type 'undefined'.ts(2322)

但是,如果我拿走React.HTMLProps,它可以工作,但那不是我想要的。有人知道解决方案吗?

提前致谢。

reactjs styled-components react-props react-proptypes
3个回答
0
投票

我认为你必须定义一个新的界面:

export interface Props extends React.HTMLProps<HTMLButtonElement> {
  size?: 'small' | 'medium' | 'large',
};

问题是React.HTMLProps或者更确切地说,它的超界面HTMLAttributes已经包含一个size属性定义为:

size?: number;

因此,您必须重命名您的财产。


0
投票

所以尝试这些,当我看着网站https://medium.com/@martin_hotell/react-typescript-and-defaultprops-dilemma-ca7f81c661c7

type Props = Partial<DefaultProps>;

type DefaultProps = Readonly<typeof defaultProps>;

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

export YourClass extends React.Component<Props> { }

这是解决问题的最简单最方便的方法,尽管如果不这样做,其他方面可能有所帮助。


0
投票

我还发现如果你想为React.HTMLProps<HTMLButtonElement> prop设置自定义值,只是扩展size不起作用。这是这个问题的解决方案。我们需要来自Omit包装的小帮手utility-typeshttps://github.com/piotrwitek/utility-types#omitt-k

并像这样使用它:

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
};
© www.soinside.com 2019 - 2024. All rights reserved.