reactjs “field”的类型未知

rsl1atfo  于 2023-05-17  发布在  React
关注(0)|答案(1)|浏览(187)

我试图部署我的代码,但当运行构建时,在TS上我得到一个“对象”是类型未知的错误,我试图找出如何解决我的情况。

export default function Home() {
  async function sendEmail(e: any) {
    e.preventDefault();

    const formData = {};
    Array.from(e.currentTarget.elements).forEach(field => {
      if ( !field.name ) return;
      formData[field.name] = field.value;
    });

    await fetch('/api/email', {
      method: 'POST',
      body: JSON.stringify(formData)
    });
    document.getElementById('emailform').onreset();
  }
  
  return (
    <form className={styles.submitformcont}  method="post" onSubmit={sendEmail} id='emailform'>
                  <label className={styles.fullnamelbl} htmlFor="name">Name:</label>
                  <br/>
                  <input className={styles.fullnamebtn} type="text" id="name" placeholder='Name'  name="name" />

                  <br/>
                  <br/>

                  <label className={styles.emaillbl} htmlFor="mail">E-mail:</label>
                  <br/>
                  <input className={styles.emailbtn}type="email" id="mail" name="email" placeholder="Enter your Email" required/>

                  <br/>
                  <br/>
                  <label className={styles.textlbl}htmlFor="msg">Message:</label>
                  <br/>
                  <textarea className={styles.textbtn} id="msg" name="Message"  placeholder="Message"></textarea>

                  <br/>

                  <button className={styles.submitbtn}> Submit </button>
    </form>
)}

'field'的类型为'unknown'. ts(18046)

yrdbyhpb

yrdbyhpb1#

e.target.elements包含button元素,您不希望收集button元素的值。所以你应该检查field的类型。仅当值为HTMLInputElementHTMLTextAreaElement时才收集该值。

import * as React from 'react';

export default function Home() {
  async function sendEmail(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const formData = {};
    Array.from(e.currentTarget.elements).forEach((field) => {
      if (
        field instanceof HTMLInputElement ||
        field instanceof HTMLTextAreaElement
      ) {
        if (!field.name) return;
        formData[field.name] = field.value;
      }
    });

    await fetch('/api/email', {
      method: 'POST',
      body: JSON.stringify(formData),
    });
    (document.getElementById('emailform') as HTMLFormElement).reset();
  }

  return (
    <form method="post" onSubmit={sendEmail} id="emailform">
      <label htmlFor="name">Name:</label>
      <input type="text" id="name" placeholder="Name" name="name" />
      <label htmlFor="mail">E-mail:</label>
      <input
        type="email"
        id="mail"
        name="email"
        placeholder="Enter your Email"
        required
      />
      <label htmlFor="msg">Message:</label>
      <textarea id="msg" name="Message" placeholder="Message"></textarea>
      <button> Submit </button>
    </form>
  );
}

stackblitz

相关问题