【问题标题】:Error TS7053 when accessing any index of the target of a React.FormEvent<HTMLFormElement>访问 React.FormEvent<HTMLFormElement> 目标的任何索引时出现错误 TS7053
【发布时间】:2021-10-16 18:54:42
【问题描述】:

基本上我正在关注这个tutorial,将其转换为 React 和 TypeScript

这是我为 onSubmit 事件编写的代码

const signUp = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();

  // Problematic lines of code
  const email = event.target[0].value;
  const password = event.target[1].value;
};

以及基本的注册表单

  return (
    <div>
      <form id="signUp" onSubmit={signUp}>
        <h3>Sign up</h3>
        <label>Email </label>
        <input type="email" name="email" />
        <label>Password </label>
        <input type="password" name="password" />
        <br></br>
        <input type="submit"></input>
      </form>
    </div>
  )

完整的错误:

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'EventTarget'.
  Property '0' does not exist on type 'EventTarget'.  TS7053

【问题讨论】:

    标签: javascript reactjs typescript react-hooks tsx


    【解决方案1】:

    您似乎理解错误。 onSubmit 事件将不包含任何输入值。要访问输入值,我建议您将它们存储在一个状态中并使用onChange 绑定它,以便在提交表单时您可以使用状态值进行验证。

    让这个工作的简短答案:

    向输入标签添加 id 属性以访问提交时的值。

    <input type="email" name="email" id="email" />
    <input type="password" name="password" id="password" />
    
    
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    

    示例:https://codesandbox.io/s/form-submit-demo-fjls0

    【讨论】:

    • 谢谢!只需要将document.getElementById 返回到HTMLInputElementHTMLElement 转换为HTMLInputElement
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    相关资源
    最近更新 更多