[英]File is replacing file, not adding in React (Next.js)
Please review my code first.请先查看我的代码。
const test = () => {
const [files, setFiles] = useState ([]);
//I think I have to edit following statement.
const handleFile = (e) => {
const newFiles = []
for (let i=0; i < e.target.files.length; i++) {
newFiles.push(e.target.files[i])
}
setFiles(newFiles)
};
return (
{files.map((file, index) => (
<div>
<div key={index}>
<p>
{file.name}
</p>
<Button size='small' onClick={() => {deleteSelectedFile(file.name)}}>
Delete
</Button>
</div>
</div>
))}
<div>
<label onChange={handleFile}>
<input type='file' multiple />+ Attach File
</label>
</div>
)
}
with handleFile statement, I can appropriately get the files.使用 handleFile 语句,我可以适当地获取文件。
However, when I upload one file at a time and then upload one file again,但是,当我一次上传一个文件然后再次上传一个文件时,
the file is not added.该文件未添加。 the file replaces file.文件替换文件。
There is not problem when I upload multiple time at once.当我一次上传多次时没有问题。
For example, I upload 'hello.jpg', and it renders well in the screen.例如,我上传了“hello.jpg”,它在屏幕上呈现得很好。 Then, I upload 'goodbye.jpg', it renders well, but 'goodbye.jpg' replaces 'hello.jpg'.然后,我上传了'goodbye.jpg',它渲染得很好,但是'goodbye.jpg'替换了'hello.jpg'。
Therefore, what I see is just 'goodbye.jpg' [button], not因此,我看到的只是 'goodbye.jpg' [按钮],而不是
'hello.jpg' [button] 'goodbye.jpg' [button] 'hello.jpg' [按钮] 'goodbye.jpg' [按钮]
. .
I want my files to stacked up, without replacing.我希望我的文件堆叠起来,而不是替换。
I need some wisdom!我需要一些智慧!
In my opinion, you only need to spread the prev state values and the files during the change event.在我看来,您只需要在更改事件期间传播 prev state 值和文件。
import { useState } from "react";
export default function App() {
const [files, setFiles] = useState([]);
const handleChange = (e) => {
// This is what you need
setFiles((prev) => [...prev, ...Object.values(e.target.files)]);
};
return (
<div>
<label onChange={handleChange}>
<input type="file" multiple />
</label>
{files.map((file) => {
return <p>{file.name}</p>;
})}
</div>
);
}
how about you don't create a new variable for new files, you just set the state for the files since it's an array你不为新文件创建一个新变量怎么样,你只需为文件设置 state 因为它是一个数组
setFiles(oldFile => [...oldFile,e.target.files[i]]);
If it's possible you can drop a codepen link如果可能,您可以删除 codepen 链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.