【发布时间】:2020-10-08 09:41:57
【问题描述】:
所以我正在开发我的 React 应用程序,并且有一点我需要上传一些文件。所以我只是使用input file 来使它工作。我将其设置为无显示,因为我希望在上传文件时点击附件图标。
问题:使用 ref 方法,一切工作正常,除了我的 hangleFileChange 函数中的一件事,当 setFiles() 设置文件变量时,组件未呈现,我看不到文件数组。但是如果我只是像这样进行文件保存
setFile(event.target.files[0])
我可以看到渲染。但是使用下面的代码,组件没有渲染
import React, { useRef, useState } from "react";
const App = () => {
const fileInput = useRef(null);
const [file, setFile] = useState([]);
const handleClick = () => {
fileInput.current.click();
};
const handleFileChange = (event) => {
console.log("Make something");
let newFiles = file;
newFiles.push(event.target.files[0]);
console.log(newFiles);
setFile(newFiles);
};
// This should run on every render
console.log("the files array is ", file);
return (
<div className="patientactions-container">
<input
type="file"
style={{ display: "none" }}
onChange={(e) => handleFileChange(e)}
ref={fileInput}
/>
<div onClick={() => handleClick()}>clck</div>
</div>
);
};
export default App;
请帮忙。
沙盒:https://codesandbox.io/s/kind-breeze-czc3w?file=/src/App.js:0-692
【问题讨论】:
-
如果我理解你的话,你想将文件推送到变量 ne 对吗?
-
变量只是临时变量。我想将用户上传的新文件附加到我的文件数组中。所以我拿了一个临时变量'ne'并复制了文件的值。然后我推送了新文件,然后是 setFile(ne)。你明白了吗?
-
让我把它贴在答案中
-
我更改了代码并使用了 setFile ( [ ...file, event.target.files[0] ] ) ;现在它正在渲染。但我仍然不明白为什么上面的代码不起作用。
标签: javascript reactjs render setstate