我有一个按钮组件.我只需在我定义的许多可选props 中传递一个onClick
props :
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
已存在,但从未发生此错误.
这里有什么问题?
Update - Types added
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>
笔记:
可能的解决方案是分解props 并添加默认props .或者使用defaultProps
从react .但不确定我是否真的需要Typescript.