【问题标题】:.reset() method results in error in typescript to reset forms.reset() 方法导致打字稿错误以重置表单
【发布时间】:2022-02-14 19:14:36
【问题描述】:

我正在使用 document.getelementbyID().reset();重置表单值。但我在打字稿中收到错误。

Property 'reset' does not exist on type 'HTMLElement'.

我正在使用这个功能:

const resetButton = () => {
    document.getElementById('compliance').reset();
}

<button onClick={resetButton}>
Reset
</button>

此功能在 javascript 中有效,但在打字稿中无效。

我该如何使用它。这些方法我都试过了,但都不管用。

1.

 (<HTMLInputElement>document.getElementById('compliance)).reset;

我收到了这个错误。

JSX element 'HTMLInputElement' has no corresponding closing tag.
let inputreset = (document.getElementById('compliance) as HTMLInputElement).reset;

我收到了这个错误。

Property 'reset' does not exist on type 'HTMLInputElement'.

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    如果您尝试重置表单,请将其转换为 HTMLFormElement,它确实具有 reset 方法 (TS playground):

    const resetButton = () => {
      (document.getElementById('compliance') as HTMLFormElement).reset();
    }
    

    一个对 React 更友好的解决方案是使用 ref:

    const form = useRef<HTMLFormElement>();
    
    const resetButton = () => {
      formRef.current?.reset(); // note conditional chaining `?.`
    }
    
    return (
      <form ref={formRef}>
        {/* Other form controls */}
      
        <button onClick={resetButton}>
        Reset
        </button>
      </form>
    )
    

    最好的解决办法是设置button type to reset,然后你就根本不需要这个函数了:

    <button type="reset">
    Reset
    </button>
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2021-06-28
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多