【发布时间】:2019-11-16 17:33:39
【问题描述】:
我有一个按钮组件。我只是在我定义的许多可选道具中只传递了一个 onClick 道具:
const Button = (props: ButtonProps) => {
const handleClick: React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement> = e => {
props.onClick(e);
}
return (
<StyledButton onClick={handleClick}>
{props.children}
</StyledButton>
);
};
那我就是这样用的:
<Button onClick={(e) => {
console.log(e);
}}>Click me!</Button>
现在,根据所提到的错误,对象怎么可能是未定义的?我清楚地将函数传递给它,并且根据类型定义也是如此。所以,我将一个对象传递给它。很简单!
...
onClick?: React.MouseEventHandler<HTMLElement>
...
我最近在这个项目中增加了一些更严格的检查,相关的是:
"strictFunctionTypes": true,
"strictNullChecks": true
strict:true 已经存在,这个错误从未发生过。
这里有什么问题?
更新 - 添加类型
export interface IBaseButtonProps {
type?: ButtonType;
disabled?: boolean;
size?: ButtonSize;
block?: boolean;
loading?: boolean | { delay?: number };
icon?: string;
className?: string;
prefixCls?: string;
children?: React.ReactNode;
}
export type AnchorButtonProps = {
href: string,
target?: string,
onClick: React.MouseEventHandler<HTMLElement>
} & IBaseButtonProps & Omit<React.AnchorHTMLAttributes<any>, 'type' | 'onClick'>;
export type NativeButtonProps = {
onClick: React.MouseEventHandler<HTMLElement>,
htmlType?: ButtonHTMLType
} & IBaseButtonProps & Omit<React.ButtonHTMLAttributes<any>, 'type' | 'onClick'>;
export type ButtonProps = Partial<AnchorButtonProps & NativeButtonProps>
注意事项:
可能的解决方案是解构道具并添加默认道具。或者使用来自 React 的 defaultProps。但不确定我是否应该对 Typescript 真正要求。
【问题讨论】:
-
onClick?: React.MouseEventHandler<HTMLElement>表示onClick可以未定义。 -
因为它是可选的?
-
删除
?以使onClick成为必需。如果它是可选的,它可以定义为未定义 -
因为我无法从
onClick中删除?,所以将defaultProps 与打字稿一起添加是个好主意吗?看来我现在必须这样做了。但是我读过很多文章来处理defaultProps只用 TS -
去掉可选标记后还是一样的人
标签: reactjs typescript