【问题标题】:error TS2322: Type '"openDialog('https://someurl.sharepoint.com/...' is not assignable to type 'EventHandler<MouseEvent<HTMLButtonElement>>错误 TS2322:类型 '"openDialog('https://someurl.sharepoint.com/...' 不可分配给类型 'EventHandler<MouseEvent<HTMLButtonElement>>
【发布时间】:2019-07-23 09:38:05
【问题描述】:

我正在尝试从 react rendor 方法调用 Javascript 函数,如下所示

        <button onClick="openDialog('https://someurl.sharepoint.com/sites/Demo/Lists/EventsCalendar/calendar.aspx')">
Office Holidays
      </button>

它给了我一个错误

[15:09:24] 错误 - typescript - src\webparts\HomeEvents\components\HomeEvents.tsx(69,13):错误 TS2322:类型 '"openDialog('https://someurl.sharepoint.com/sites/Demo/Lists/EventsCal...' 不可分配输入“EventHandler>”。

【问题讨论】:

  • 您正在调用一个函数并将该函数的值传递给onClick。您需要将函数传递给 onClick 而不是函数中的值
  • 是的,我知道,但是如果我直接调用该函数,那么它需要在组件中未定义的函数定义,而不是定义到 js 文件中

标签: reactjs typescript button onclick render


【解决方案1】:

您以错误的方式将函数传递给onClick。你需要改变你的onClick函数如下

 <button onClick={() => openDialog('https://someurl.sharepoint.com/sites/Demo/Lists/EventsCalendar/calendar.aspx')}>
Office Holidays
      </button>

【讨论】:

  • 这会给我一个错误“事件”类型上不存在属性“openDialog”
  • 在这种情况下,您需要将 openDialog 函数导入到您的组件文件中
  • 我该怎么做?作为写在JS文件中的函数
  • 文件中有function openDialog函数,把你的函数改成export function openDialog。然后在你的组件文件import { openDialog } from 'path-to-open-dialog-file';
  • 请将"allowJS": true 添加到您的"compilerOptions" 文件中的tsconfig.json 文件中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 2019-02-07
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多