如何使用反应钩子将文件放入状态变量中

aka*_*no1 2 javascript ecmascript-6 reactjs

我正在尝试使用 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)}
/>
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

Uncaught TypeError: picture is not iterable
Run Code Online (Sandbox Code Playgroud)

当我将 onChangePicture 更改为

setPicture(picture, e.target.files[0]) 
Run Code Online (Sandbox Code Playgroud)

图片变量未定义,

任何帮助,将不胜感激。

GG.*_*GG. 9

对于来到这里寻找如何使用 TypeScript 进行操作的任何人:

const [file, setFile] = useState<File>();

const onChange = (event: React.FormEvent) => {
    const files = (event.target as HTMLInputElement).files

    if (files && files.length > 0) {
        setFile(files[0])
    }
}
Run Code Online (Sandbox Code Playgroud)


apo*_*fos 6

我想你的意思是:

setPicture([...picture, e.target.files[0]]);
Run Code Online (Sandbox Code Playgroud)

这会将第一个文件连接到所有当前文件。

请记住使用const [picture, setPicture] = useState([]);as 以确保它不会在第一次中断


Ram*_*ore 5

您可以将值直接传递给 setPicture 函数来设置状态变量图片。

尝试:

const [picture, setPicture] = useState(null);

const onChangePicture = e => {
    console.log('picture: ', picture);
    setPicture(e.target.files[0]);
};

<input
  type="file"
  //style={{ display: 'none' }}
  onChange={onChangePicture}
/>
Run Code Online (Sandbox Code Playgroud)