如何处理打字稿中的elements.namedItem?

时间:2020-05-26 01:34:26

标签: reactjs typescript

我有一个表单,正在尝试访问onSubmit事件的target.elements

这是代码:

// ref
const formRef = React.useRef<HTMLFormElement>(null);

// handleSubmit
const handleSubmit = () => {
  if (formRef.current?.elements) {
    const email = formRef.current.elements.namedItem('loginEmail') as HTMLInputElement;
    console.log(email.value);
    // is that how I'm supposed to access the `email.value` by using as HTMLInputElement? 
  }
}

// render form
<form ref={formRef} onSubmit={handleSubmit}>
  <input name="loginEmail" />
  <button type="submit">submit</button>
</form>

0 个答案:

没有答案