简体   繁体   English

打字稿抱怨反应组件可选道具可能未定义

[英]Typescript complains that react component optional prop could possibly be undefined

I have a simple React component like this:我有一个像这样的简单 React 组件:

interface ComponentProps {
    onClick?: () => void;
}

const Component = (props: ComponentProps) => {
    if (!props.onClick) {
        return <></>;
    }

    return (
        // Typescript complains: Cannot invoke an object which is possibly 'undefined'.ts(2722)
        <button onClick={() => props.onClick()}>  
            test
        </button>
    );
};

Typescript complains props.onClick could be undefined, even if after the check. Typescript 抱怨 props.onClick 可能未定义,即使在检查之后也是如此。

Could anyone help me to understand why props.onClick can still possibly be undefined?谁能帮我理解为什么 props.onClick仍然可能是未定义的?

This is because you are using the optional property operator ?这是因为您使用的是可选的属性运算符? into the ComponentProps interface definition.进入ComponentProps接口定义。

I see two ways to solve this issue:我看到有两种方法可以解决这个问题:

The first one is to change the optional property definition to mandatory removing the ?第一个是将可选属性定义更改为强制删除? optional property operator, so you don't need to validate if the onClick function is passed to the component.可选的属性运算符,因此您无需验证onClick函数是否传递给组件。

interface ComponentProps {
   onClick: () => void;
}
const Component = ({onClick}) => (
   <button onClick={onClick}>
       test
   </button> 
)

l The second one is to create a handler function in order to validate the optional onClick function. l 第二个是创建一个处理函数来验证可选的onClick函数。

inteface ComponentProps {
    onClick?: () => void;
}
const Component = ({onClick}: ComponentProps) => (
   <button onClick={() => {
       if(onClick) onClick();
   }}>  
       test
   </button>
)

Bonus.奖金。 You can use spread syntax and ternary operator together to validate optional properties passed to the React component.您可以同时使用扩展语法和三元运算符来验证传递给 React 组件的可选属性。

interface ComponentProps {
   onClick?: () => void;
}
const Component = ({onClick}: ComponentProps) => (
   <button {...(onClick ? {onClick} : {})}>test</button>
)

The problem is that your props object is mutable and TypeScript assumes that it can be modified between your !props.onClick check and the execution of the callback.问题是你的props对象是可变的,TypeScript 假设它可以在你的!props.onClick检查和回调执行之间修改。

To fix your issue, you can destructure the props object and use the onClick attribute as a scoped variable:要解决您的问题,您可以解构props对象并将onClick属性用作范围变量:

const Component = ({onClick}: ComponentProps) => {
    if (!onClick) {
        return <></>;
    }

    return (
        <button onClick={() => onClick()}>  
            test
        </button>
    );
};

Why don't you try你为什么不试试

interface ComponentProps {
    onClick?: () => void;
}

const Component = ({ onClick = () => {}}: ComponentProps) => {


    return (
      
        <button onClick={() => props.onClick()}>  
            test
        </button>
    );
};

use props.onClick?.() instead of props.onClick() .使用props.onClick?.()而不是props.onClick()

This tells typescript to call onClick() only if it is defined.这告诉打字稿只有在定义时才调用 onClick() 。

Learn more about optional chaining here 在此处了解有关可选链接的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 react 和 typescript 修复错误 object 可能未定义? - How to fix the error object could be possibly undefined using react and typescript? Object 可能是可选链接上的“未定义”错误 Typescript - Object is possibly 'undefined' Error on Optional Chaining Typescript Typescript React:使用传递给同一组件的另一个道具有条件地将道具标记为可选或强制性 - Typescript React: Conditionally mark prop to optional or mandatory using another prop passed to same component 即使我使用'? 可选运算符和 '| 不明确的' - React typescript props not showing as possibly defined, even when I use '?' optional operator and '| undefined' 反应 typescript state Object 可能是“未定义”错误 - react typescript state Object is possibly 'undefined' error React Tooltip 组件与 TypeScript 在我的 useRef 元素上出现“可能未定义”错误,不知道如何修复 - React Tooltip component with TypeScript getting a 'Possibly Undefined' error on my useRef element, not sure how to fix 无状态React组件的prop类型的Typescript错误 - Typescript error on prop types of stateless React Component 限制 Typescript 中 React Component prop 的类型 - Restrict the type of React Component prop in Typescript 如何将 ReactNode 定义为打字稿反应组件的道具? - How to Define ReactNode as a prop for a typescript react component? 如何在组件(React + TypeScript)中输入链接属性? - How to type link prop in component (React + TypeScript)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM