我一直在尝试以表格形式提交文件(图像)和测验。它们都有单独的按钮,但是必须首先按下文件按钮,才能将图像路径添加到问题发布数据状态。
但是,由于某些原因,页面上传第二张或第三张后会刷新。这仅在上传文件时发生。
// image upload form
<form onSubmit={handleImageUpload} encType="multipart/form-data">
<input
type="file"
name="photo"
onChange={handleFileChange}
/>
<button type="submit" className="btn"> submit </button>
</form>
const handleImageUpload = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('photo', file);
axios.post(uploadAPI, formData).then(res => setPost({...post, image: res.data.file}));
}
答案 0 :(得分:0)
将onClick
交换到handle函数并进行onSubmit
调用e.preventDefault()
解决了我在页面上具有多种形式并在连续提交不同形式之后随机刷新的问题。
<form onSubmit={(e) => {e.preventDefault()}} encType="multipart/form-data">
<input
type="file"
name="photo"
onChange={handleFileChange}
/>
<button type="submit" className="btn" onClick={handleImageUpload}> submit </button>
</form>