【问题标题】:Add type for onClick property which is in ...props in React TypeScript为 React TypeScript 中的 ...props 中的 onClick 属性添加类型
【发布时间】:2021-05-10 09:59:12
【问题描述】:

我有一个按钮组件,我正在尝试使用type 编写道具类型,我在控制台中看到了这个错误。有人可以帮忙吗?

Type '{ children: string; label: string; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & Props'.
  Property 'onClick' does not exist on type 'IntrinsicAttributes & Props'.  TS2322

摘自我的代码

type Props = {
  label: string;
  children: ReactNode;
};

const Button = ({ label, children, ...props }: Props) => (
  <button label={label} {...props}>
    {children}
  </button>
);

【问题讨论】:

    标签: javascript reactjs typescript ecmascript-6


    【解决方案1】:

    您需要将onClick 添加到Props 中,例如:

    type Props = {
      label: string;
      children: ReactNode;
      onClick: () => void;
    };
    

    【讨论】:

    • 看起来错误不再存在。但是,如果我没有为Button 组件传递标签,它会说label 类型缺失。有没有办法让它成为可选的?
    • label?: string
    猜你喜欢
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2019-07-19
    • 2023-03-26
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多