【问题标题】:Property 'focus' does not exist on 'Element'?“元素”上不存在属性“焦点”?
【发布时间】:2020-01-06 15:22:12
【问题描述】:

创建键盘导航,遇到以下问题:

let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
  currentActive.previousElementSibling.focus();
}

代码按预期工作,但 TypeScript 抱怨 Property 'focus' does not exist on 'Element'? - currentActive<img /> 标记。

我尝试将 currentActive 分配为 HTMLElement,这样做: let currentActive = document.activeElement as HTMLCollectionOf<HTMLElement>,不过好像不太喜欢。

我错过了什么?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    我建议尝试这样的事情:

    let currentActive = document.activeElement;
    if (e.key === "ArrowLeft") {
      (currentActive.previousElementSibling as HTMLElement)?.focus();
    }
    

    请注意,自 TypeScript 3.7 起可选链接可用

    【讨论】:

    • 很好的解决方案!不幸的是,运行的是旧版本的 TS :(
    • 但是为什么会这样呢? TS 不知道它不是 HTMLElement 吗?
    【解决方案2】:

    你需要让 TS 相信 currentActive.previousElementSibling 的类型是 HTMLElement

    作为奖励提示,我建议您说服自己并避免控制台中出现一些红十字。也许类似于currentActive?.previousElementSibling?.focus?.();

    【讨论】:

    • focus?.() 应该是 .focus()。编辑队列已满,否则我将编辑答案。
    • 我不太确定,previousElementSibling 返回一个元素并且并非所有元素都有焦点方法。
    • 是的。我可以确认此解决方案不适用于 mat-checkbox 等元素
    【解决方案3】:

    我遇到了同样的问题,我通过定义 queryselector 所期望的元素类型解决了这个问题。在我的情况下,我期待一个 input 元素,所以我做到了:

    document.querySelector<HTMLInputElement>(`input[name=${element-name}]`)?.focus()
    

    【讨论】:

      【解决方案4】:

      使用as 告诉 TS 它是一个 HTMLElement:

      (currentActive.previousElementSibling as HTMLElement).focus();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-30
        相关资源
        最近更新 更多