小编典典

反应-表单提交后清除输入值

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;

阅读 199

收藏
2020-07-22

共1个答案

小编典典

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

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
      city: ''
    });
}
2020-07-22