表单提交后清除输入值

表单提交后清除输入值

本文介绍了React - 表单提交后清除输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm presented with a rather silly problem. I am in the process of creating my first React application and I have encountered a little issue, where I am not able to clear my input value, after I submit a form. A tried googling this problem, found some similar threads here, but I was not able to resolve this. I do NOT want to change the state of my component/application, just to change the value of the input to an empty string. I tried clearing the value of the input in my onHandleSubmit() function, but I got an error:

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

我的 SearchBar 组件:

My SearchBar Component:

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;

推荐答案

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

You are having a controlled component where input value is determined by this.state.city. So once you submit you have to clear your state which will clear your input automatically.

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

这篇关于React - 表单提交后清除输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:16