我遇到了一个相当愚蠢的问题。我正在创建我的第一个 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;