如何正确使用不必要的onClick事件?
interface IUIText {
children: ReactNode;
type: string;
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
const UIText = (props: IUIText) => {
return (
<div onClick={(e) => props.onClick(e)}> //Cannot invoke an object which is possibly 'undefined'.
{props.children}
</div>
);
};
用法:
<UIText type={'solid'} onClick={e => clickHandler(e)}>Gallery</UIText>
但我也可以使用它没有onClick事件:
<UIText type={'primary'}>Gallery</UIText>
您也可以使用逻辑与(&&)
interface IUIText {
children: ReactNode;
type: string;
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
const UIText = (props: IUIText) => {
return (
<div onClick={(e) => props.onClick && props.onClick(e)}>
{props.children}
</div>
);
};
您必须执行空检查。你的onClick不是"不必要的",而是"可空的">
interface IUIText {
children: ReactNode;
type: string;
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
const UIText = (props: IUIText) => {
return (
<div onClick={(e) => {
if(props.onClick) props.onClick(e); // just check for onClick
}}>
{props.children}
</div>
);
};