如何重置ReactJS文件输入

Ste*_*nko 23 html5 file-upload reactjs

我有文件上传输入:

<input onChange={this.getFile} id="fileUpload" type="file" className="upload"/>
Run Code Online (Sandbox Code Playgroud)

我这样处理上传:

getFile(e) {
    e.preventDefault();
    let reader = new FileReader();
    let file = e.target.files[0];
    reader.onloadend = (theFile) => {
        var data = {
            blob: theFile.target.result, name: file.name,
            visitorId:  this.props.socketio.visitorId
        };
        console.log(this.props.socketio);
        this.props.socketio.emit('file-upload', data);
    };
    reader.readAsDataURL(file);
}
Run Code Online (Sandbox Code Playgroud)

如果我上传同一个文件两次,则不会触发上传事件.我该如何解决这个问题?对于简单的js代码,只需执行以下操作即可:this.value = null; 在变更处理程序.我怎么能用ReactJS做到这一点?

Fre*_*eez 48

我想你可以像这样清除输入值:

e.target.value = null;
Run Code Online (Sandbox Code Playgroud)

文件输入无法控制,没有React特定的方法来做到这一点.

  • 对于打字稿,需要 // @ts-ignore (4认同)
  • 注意:在 Chrome 79 中设置“未定义”会触发此错误:“未捕获的 DOMException:无法在“HTMLInputElement”上设置“值”属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串。”。**但是 `null` 不会触发错误。** (2认同)

Joz*_*car 29

这项工作对我来说 - ref = {ref => this.fileInput = ref}

<input id="file_input_file" type="file" onChange={(e) => this._handleFileChange(e)} ref={ref=> this.fileInput = ref} />
Run Code Online (Sandbox Code Playgroud)

在我的情况下,一旦文件上传到服务器,我通过使用下面的语句清除它

 this.fileInput.value = "";
Run Code Online (Sandbox Code Playgroud)


Poo*_*oja 19

import React, { useRef } from "react";

export default function App() {
  const ref = useRef();

  const reset = () => {
    ref.current.value = "";
  };

  return (
    <>
      <input type="file" ref={ref} />
      <button onClick={reset}>reset</button>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)


ton*_*hnb 18

对我有用的是key为文件输入设置属性,然后当我需要重置它时,我更新了键属性值:

functionThatResetsTheFileInput() {
  let randomString = Math.random().toString(36);

  this.setState({
    theInputKey: randomString
  });
}

render() {
  return(
    <div>
      <input type="file"
             key={this.state.theInputKey || '' } />
      <button onClick={this.functionThatResetsTheFileInput()} />
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

这迫使React再次从头开始渲染输入.

  • 工作起来就像一个魅力。我用了 `key={Date.now()}` (3认同)

Eln*_*oor 11

每次点击onClick都可以重置输入,这样即使是同一个文件onChange也会被触发。

<input onChange={this.onChange} onClick={e => (e.target.value = null)} type="file" />
Run Code Online (Sandbox Code Playgroud)


ael*_*lor 9

我通过key在文件输入内部进行更新来实现。这将强制重新渲染,并且先前选择的文件将消失。

<input type="file" key={this.state.inputKey} />
Run Code Online (Sandbox Code Playgroud)

更改状态inputKey将重新渲染组件。更改此值的一种方法inputKey是始终将其设置为Date.now()单击应该清除该字段的按钮。


Dan*_*lem 8

以下使用 React Hooks 对我有用。这是使用所谓的“受控输入”完成的。这意味着,输入由状态控制,或者它们的真实来源是状态。

TL;DR重置文件输入是一个使用钩子useState()useRef()钩子的两步过程。

注意:我还包括了如何重置文本输入以防其他人好奇。

function CreatePost({ user }) {
    const [content, setContent] = React.useState("");
    const [image, setImage] = React.useState(null); //See Supporting Documentation #1
    const imageInputRef = React.useRef(); //See Supporting Documentation #2

    function handleSubmit(event) {
        event.preventDefault(); //Stop the pesky default reload function
        setContent(""); //Resets the value of the first input - See #1

        //////START of File Input Reset
        imageInputRef.current.value = "";//Resets the file name of the file input - See #2
        setImage(null); //Resets the value of the file input - See #1
        //////END of File Input Reset
    }

    return (
    <div>
        <form onSubmit={handleSubmit}>
            <input 
            type="text" 
            placeholder="Add Post Content" 
            onChange={event => setContent(event.target.value)}
            value={content} //Make this input's value, controlled by state
            />
            <input 
            type="file"
            onChange={event => setImage(event.target.files[0])} //See Supporting Doc #3
            ref={imageInputRef} //Apply the ref to the input, now it's controlled - See #2
            />
            <button type="submit">Submit Form</button>
        </form>
    </div>
    )
};
Run Code Online (Sandbox Code Playgroud)

支持文档:

  1. 使用状态钩子
    • 返回一个有状态的值和一个更新它的函数。
  2. 使用引用钩子
    • 如果您将 ref 对象传递给 React,则每当该节点发生更改时,React 都会将其当前属性设置为相应的 DOM 节点。
  3. 使用来自网络应用程序的文件
    • 如果用户只选择一个文件,则只需要考虑列表的第一个文件。

  • 这应该是公认的答案,因为这是重置输入的更多 React 方式。我在另一个组件中有输入,我可以使用 useRef 轻松重置它。我不需要选择输入或监听任何事件。 (2认同)

小智 6

如果您知道您根本不会使用内置文件输入值,您也可以将它包含在您的输入元素中。

<input value={""} ... />
Run Code Online (Sandbox Code Playgroud)

通过这种方式,值总是在渲染时重置为空字符串,并且您不必笨拙地将它包含在 onChange 函数中。