React - 在表单提交后清除输入值

Tom*_*Vee 22 javascript forms input submit reactjs

我遇到了一个相当愚蠢的问题.我正在创建我的第一个React应用程序,我遇到了一个小问题,在提交表单后我无法清除输入值.一个尝试谷歌搜索这个问题,在这里发现了一些类似的线程,但我无法解决这个问题.我不想更改组件/应用程序的状态,只是将输入值更改为空字符串.我尝试清除函数中的输入值onHandleSubmit(),但是我收到了一个错误:

"无法设置未定义的属性'值'".

我的SearchBar组件:

import React, { Component } from "react";

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      city: ""
    };

    this.onHandleChange = this.onHandleChange.bind(this);
    this.onHandleSubmit = this.onHandleSubmit.bind(this);
  }

  render() {
    return (
      <form>
        <input
          id="mainInput"
          onChange={this.onHandleChange}
          placeholder="Get current weather..."
          value={this.state.city}
          type="text"
        />
        <button onClick={this.onHandleSubmit} type="submit">
          Search!
        </button>
      </form>
    );
  }

  onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }
}

export default SearchBar;
Run Code Online (Sandbox Code Playgroud)

Pan*_*her 26

您有一个受控组件,其中input值由确定this.state.city.因此,一旦提交,您必须清除您的状态,这将自动清除您的输入.

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
      city: ''
    });
}
Run Code Online (Sandbox Code Playgroud)


Shu*_*tri 9

由于输入字段是受控元素,因此无法在不修改状态的情况下直接更改输入字段值.

也在

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }
Run Code Online (Sandbox Code Playgroud)

this.mainInput因为mainInput是一个id,所以不引用输入,你需要为输入指定一个ref

<input
      ref={(ref) => this.mainInput= ref}
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      value={this.state.city}
      type="text"
    />
Run Code Online (Sandbox Code Playgroud)

在当前状态下,最好的方法是清除状态以清除输入值

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({city: ""});
  }
Run Code Online (Sandbox Code Playgroud)

但是,如果您仍然出于某种原因想要将值保持在状态,即使提交了表单,您也希望不加控制地输入

<input
      id="mainInput"
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      type="text"
    />
Run Code Online (Sandbox Code Playgroud)

并更新状态中的值onChangeonSubmit使用清除输入ref

 onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }
Run Code Online (Sandbox Code Playgroud)

话虽如此,我认为保持国家不变没有任何意义,所以第一个选择应该是要走的路.