如何正確使用不必要的 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>
uj5u.com熱心網友回復:
您還可以使用邏輯 AND (&&) 進行檢查
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>
);
};
uj5u.com熱心網友回復:
您將必須執行空檢查。您的 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>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464702.html
下一篇:將列舉元素映射到型別
