我为我的按钮样式组件的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,它可以工作,但这不是我想要的。有没有人知道解决这个问题的办法?
提前谢谢。
发布于 2019-02-13 12:48:28
我认为你必须定义一个新的接口:
export interface Props extends React.HTMLProps<HTMLButtonElement> {
size?: 'small' | 'medium' | 'large',
};
问题是React.HTMLProps
,或者更确切地说,它的超级接口HTMLAttributes
已经包含了一个size
属性,其定义如下:
size?: number;
因此,您必须重命名您的属性。
发布于 2019-04-10 13:55:02
我还发现,如果您想为size
属性设置自定义值,简单地扩展React.HTMLProps<HTMLButtonElement>
是不起作用的。这里有一个解决这个问题的方法。我们将需要来自utility-types
包(https://github.com/piotrwitek/utility-types#omitt-k)的名为Omit
的小助手。
并像这样使用它:
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
};
发布于 2019-02-13 13:07:29
因此,在我查看站点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> { }
这可能是解决问题的最简单、最容易的方法,尽管如果这不起作用,还有其他方法可能会有所帮助。
https://stackoverflow.com/questions/54670121
复制