[英]TypeScript: Cannot invoke an object which is possibly 'undefined'
I've a reusable component that accepts an optional onClick callback function as a prop.我有一个可重用的组件,它接受可选的 onClick 回调 function 作为道具。
I've defined the Props interface as folllows:我将 Props 接口定义如下:
interface Props {
prop1: string;
prop2: string;
optionalClickFn?: () => void;
}
The functional React (JSX) component as follows:功能性 React (JSX) 组件如下:
const ExampleComponent = (props: Props) => {
return{
{ props.optionalClickFn ? <div
className="delete-btn"
onClick={() => props.optionalClickFn()}
>
<FontAwesomeIcon icon={faTimesCircle} color="red" />
</div> : <div></div>}
}
}
I've defined an optional prop 'optionalClickFn', therefore I am first checking if it exist before executing the function.我已经定义了一个可选的 prop 'optionalClickFn',因此我在执行 function 之前首先检查它是否存在。 However, i still get the error: Cannot invoke an object which is possibly 'undefined'.
但是,我仍然收到错误消息:无法调用可能是“未定义”的 object。
I found the solution.我找到了解决方案。 Making the check that way was not working.
以这种方式进行检查是行不通的。 If I put another if condition inside the onClick prop, it works as expected.
如果我在 onClick 道具中放置另一个 if 条件,它会按预期工作。
{props.optionalClickFn ? (
<div
className="delete-btn"
onClick={() => {
if (props.optionalClickFn) {
return props.optionalClickFn();
}
}}
>
<FontAwesomeIcon icon={faTimesCircle} color="red" />
</div>
) : <div></div>}
I'm still unsure why it doesn't work the way I wrote in the original question though.我仍然不确定为什么它不像我在原始问题中写的那样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.