简体   繁体   English

TypeScript:无法调用可能是“未定义”的 object

[英]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.

相关问题 对象是在没有类的方法的情况下创建的。 打字稿错误:无法调用可能是“未定义”的对象。 ts(2722) - An object is created without a method of a class. Typescript error: Cannot invoke an object which is possibly 'undefined'. ts(2722) 为什么 TypeScript 在可选链接运算符后显示“无法调用 object 这可能是'未定义'.ts(2722)”错误? - Why is TypeScript showing “Cannot invoke an object which is possibly 'undefined'.ts(2722)” error after optional chaining operator? TS2722:无法调用可能“未定义”的对象 - TS2722: Cannot invoke an object which is possibly 'undefined' 无法调用子组件中可能“未定义”的对象 - Cannot invoke an object which is possibly 'undefined' in children component 打字稿:对象可能是“未定义” - Typescript: Object is possibly 'undefined' Object 可能在 TypeScript 中未定义 - Object is possibly undefined in TypeScript 对象可能是“未定义”打字稿 - Object is possibly 'undefined' typescript 无法调用可能未定义的对象 - Cannot Invoke an Object which is possible undefined “对象可能是&#39;未定义的&#39;”在reactjs中使用typescript - “Object is possibly 'undefined'” in reactjs with typescript 对象可能在带有 TypeScript 的 Vuex 突变中“未定义” - Object is possibly 'undefined' in Vuex mutation with TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM