React:提交表单后如何清除文件输入和数据输入字段?

dan*_*boy 3 reactjs

在我提交包含数据字段和文件字段的表单后,仅清除数据字段,但保留上传的文件字段。看图:这里

OnChange 函数

    onChange = (e) => {
        if(e.target.name === 'audio') {
            this.setState({
                [e.target.name]: e.target.files[0], loaded: 0,
            }, () => console.log(this.state.audio))

        } else {

            this.setState({
                [e.target.name]: e.target.value
            }, () => console.log(this.state))
        }
    }
Run Code Online (Sandbox Code Playgroud)

提交功能


      onSubmit = e => {
    e.preventDefault();
    let { title, content, audio} = this.state;
    //const story = { title, content, audio};
    let formDataStory = new FormData();
    formDataStory.append('audio', audio);
    formDataStory.append('title', title);
    formDataStory.append('content', content);
    this.props.addStory(formDataStory);
    this.setState({
      title: "",
      content:"",
      audio: ""
    });
  };

Run Code Online (Sandbox Code Playgroud)

形式

  render() {
    const {title, content, audio} = this.state;
    return (
      <div className="card card-body mt-4 mb-4">
        <h2>Add Story</h2>
        <form onSubmit={this.onSubmit}>

          <div className="form-group">
            <label>Title</label>
            <input
              className="form-control"
              type="text"
              name="title"
              onChange={this.onChange}
              value={title}
            />
             </div>
           <div className="form-group">
            <label>Content</label>
            <input
              className="form-control"
              type="text"
              name="content"
              onChange={this.onChange}
              value={content}
            />
          </div>

           <div className="form-group">
            <label>Audio</label>
            <input
              className="form-control"
              type="file"
              name="audio"
              onChange={this.onChange}
              //value={audio}
            />
          </div>

         <div className="form-group">
            <button type="submit" className="btn btn-primary">
              Submit
            </button>
          </div>
        </form>
      </div>
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

提交表单后,如何将文件上传字段与其他数据字段一起重置?

非常感谢!

Cam*_*tle 6

由于file输入始终不受控制,因此您需要使用domref并手动清除该值。

这是执行此操作的示例功能组件:

function ExampleFileInput() {
  const ref = React.useRef();
  function handleClick() {
    ref.current.value = ""
  }
  return (
    <div className="App">
      <input type="file" ref={ref}/><br />
      <button type="button" onClick={handleClick}>Clear file</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

要在类组件中使用,请参阅文档。您可以在此问题中阅读有关清除文件输入的更多方法。