即使代码运行无误,ReactJs表单也不会显示在浏览器中

hyrbngr7  于 2023-01-17  发布在  React
关注(0)|答案(2)|浏览(159)

我为一个表单编写了这段代码来收集图像和文本数据,它运行良好,没有任何错误,但在浏览器中,除了一个空白屏幕外什么也没有显示。

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useDropzone } from 'react-dropzone';

const Form = () => {
  const { register, handleSubmit } = useForm();
  const [images, setImages] = useState([]);
  const { getRootProps, getInputProps } = useDropzone({
    accept: 'image/*',
    onDrop: acceptedImages => {
      setImages(acceptedImages.map(image => Object.assign(image, {
        preview: URL.createObjectURL(image)
      })));
    }
  });

  const onSubmit = async data => {
    const formData = new FormData();
    images.forEach(image => {
      formData.append('images', image);
    });
    formData.append('name', data.name);
    formData.append('description', data.description);

    try {
      const response = await fetch('http://localhost:8000/submit-form', {
        method: 'POST',
        body: formData
      });
      console.log(response);
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div {...getRootProps()}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <br />
      {images.map(image => (
        <img key={image.name} src={image.preview} alt={image.name} style={{ width: '200px' }} />
      ))}
      <br />
      <input name="name" ref={register} placeholder="Name" />
      <br />
      <textarea name="description" ref={register} placeholder="Description" />
      <br />
      <button type="submit">Submit</button>
    </form>
    
  );
}

export default Form

我希望在浏览器中看到一个表单,至少看看它是否真的工作,但我什么也没看到。我在表单上使用了react Dropzone和react hook form。也许还可以获取数据。

mwngjboj

mwngjboj1#

尝试更改input和textarea标签中的ref,如下所示:

<input name="name" {...register('name')} placeholder="Name" />
<textarea name="description" {...register('description')} placeholder="Description" />

参考:https://react-hook-form.com/get-started/

vawmfj5a

vawmfj5a2#

我怀疑您没有调用e.preventDefault()来阻止默认表单提交。因此,您可以尝试以下操作:
替换以下语句:

<form onSubmit={handleSubmit(onSubmit)}>

<form onSubmit={handleSubmit}>

handleSubmit函数更改为:

const onSubmit = e => {
  e.preventDefault(); //prevent submit form
  let form = e.target; //get the form obj  
  const formData = new FormData();
images.forEach(image => {
  formData.append('images', image);
});   
    formData.append('name', form.name.value);
    formData.append('description', form.description.value);
   ..............................  
}

相关问题