我正在尝试使用 React hooks 上传图片
const [picture, setPicture] = useState();
const onChangePicture = e => {
console.log('picture: ', picture);
setPicture(...picture, e.target.files[0]);
};
<input
type="file"
//style={{ display: 'none' }}
onChange={e => onChangePicture(e)}
/>
但是我收到以下错误:
Uncaught TypeError: picture is not iterable
当我将 onChangePicture 更改为
setPicture(picture, e.target.files[0])
图片变量未定义,
如有任何帮助,我们将不胜感激。
最佳答案
我认为你的意思是:
setPicture([...picture, e.target.files[0]]);
这会将第一个文件连接到所有当前文件。
记住使用const [picture, setPicture] = useState([]);
以确保它不会在第一次中断
关于javascript - 如何使用 react 钩子(Hook)将文件放入状态变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56629481/