简体   繁体   English

表单提交后如何清除输入(反应)

[英]How to clear input after form submit (React)

I have a search input I'd like to clear after the value is submitted and the search is performed with the value. 提交值并使用值执行搜索后,我想清除搜索输入。 In similar questions, it was suggested to set the state of the input value to '' , but I think that's what I tried and it didn't do anything. 在类似的问题中,建议将输入值的状态设置为'' ,但是我认为这就是我尝试过的方法,它什么也没做。

I only have a parent and child component in my app. 我的应用程序中只有一个父级和子级组件。 The parent component has a method for searching jokes ( searchJokes ), and it is passed down as a prop with a different name to the child component in the component instance with onFormSubmit={this.searchJokes} . 父组件具有一种用于搜索笑话的方法( searchJokes ),并且它作为道具以与onFormSubmit={this.searchJokes}的组件实例中的子组件不同的名称向下传递。 In the child component, when the user enters something into the search input, its event.target.value is passed with onChange={e => props.onInputChange(e.target.value)} corresponding to the onSearchChange method in the parent prop, and the value is used to update the state of searchTerm . 在子组件中,当用户在搜索输入中输入内容时,其event.target.value会通过与父prop中的onSearchChange方法相对应的onChange={e => props.onInputChange(e.target.value)}传递,并且该值用于更新searchTerm的状态。

I added searchTerm: '' to the end of the searchJokes method, which fetches a search according to the search term, as you can see in the parent component code below. 我在searchJokes方法的末尾添加了searchTerm searchTerm: '' ,该方法根据搜索项获取搜索,如下面的父组件代码所示。

Parent component: 父组件:

class App extends Component {
  constructor() {
    super();

    this.state = {
      searchTerm: '',
      jokes: [],
      isFetchingJokes: false,
      isSearch: false
    };

    this.onSearchChange = this.onSearchChange.bind(this);
    this.randomizeJokes = this.randomizeJokes.bind(this);
    this.searchJokes = this.searchJokes.bind(this);
  }

  randomizeJokes() {
    this.setState({
      isFetchingJokes: true,
      isSearch: false
    });

    fetch(
      'https://icanhazdadjoke.com/',
      {
        method: 'GET',
        headers: {
          Accept: 'application/json'
        }
    })
      .then(response => response.json())
      .then(json => {
        let joke = json.joke;
        this.setState({
          joke,
          isFetchingJokes: false
        });
      });
  }

  searchJokes(limit = 15) {
    // If nothing entered, user gets "Please fill out this field" message due to "required" attribute on input element
    if (this.state.searchTerm !== '') {
      this.setState({
        isFetchingJokes: true,
        isSearch: true
      });

      fetch(
        `https://icanhazdadjoke.com/search?term=${
          this.state.searchTerm
        }&limit=${limit}`,
        {
          method: 'GET',
          headers: {
            Accept: 'application/json'
          }
      })
        .then(response => response.json())
        .then(json => {
          let jokes = json.results;
          this.setState({
            jokes,
            isFetchingJokes: false,
            searchTerm: '' // <-- DOESN'T CLEAR INPUT
          });
        });
    }
  }

  onSearchChange(value) {
    this.setState({ searchTerm: value });
  }

  jokeRender() {
    return (
      <div>
        {this.state.isSearch ?
          <ul>{this.state.jokes.map(item => <li key={item.id}>{item.joke}</li>)}
          </ul> : <p className="random-joke">{this.state.joke}</p>}
      </div>
    );
  }

  render() {
    return (
      <div>
        <h1>Dad Jokes</h1>
        <RetrievalForm
          onFormSubmit={this.searchJokes}
          onInputChange={this.onSearchChange}
          isSearching={this.state.isFetchingJokes}
          onRandomize={this.randomizeJokes}
        />

        {this.state.isFetchingJokes ? <p className="searching-message">Searching for jokes...</p> : this.jokeRender()}
      </div>
    );
  };
}

Child component: 子组件:

const RetrievalForm = props => {
  const onSubmit = e => {
    // Prevents GET request/page refresh on submit
    e.preventDefault();
    props.onFormSubmit();
  };

  return (
    <>
      <form onSubmit={onSubmit}>
        <input
          type="text"
          placeholder="Enter search term..."
          onChange={e => props.onInputChange(e.target.value)}
          required
        />
        <div>
          {/* Specifying type here since it's good practice; different browsers may use default types for buttons */}
          <button type="submit" disabled={props.isSearching}>Search</button>
          {/* type="button" stops input validation message from being displayed (on Firefox) when randomize button is clicked without anything entered */}
          <button type="button" onClick={props.onRandomize} disabled={props.isSearching} className="randomize-button">
            Randomize
          </button>
        </div>
      </form>
    </>
  );
};

Any help would be greatly appreciated. 任何帮助将不胜感激。

您需要将searchTerm向下传递到RetrievalForm,并在该输入集中将value = {searchTerm}设置为该值将绑定到该状态。

Basically, you need to store the input value in the component's state. 基本上,您需要将输入值存储在组件的状态中。 When onSubmit is called, we should revert that value to an empty string. 调用onSubmit时,我们应该将该值恢复为空字符串。

Example with some React Hooks goodness: 具有一些React Hooks优点的示例:

import React, { Component, useState } from 'react';

const RetrievalForm = props => {
  const [searchTerm, setSearchTerm] = useState('');

  const onChange = e => {
    const { value } = e.target;
    props.onInputChange(value);
    setSearchTerm(value)
  }

  const onSubmit = e => {
    // Prevents GET request/page refresh on submit
    e.preventDefault();
    props.onFormSubmit();
    setSearchTerm('');
  };

  return (
    <>
      <form onSubmit={onSubmit}>
        <input
          type="text"
          value={searchTerm}
          placeholder="Enter search term..."
          onChange={onChange}
          required
        />
        <div>
          {/* Specifying type here since it's good practice; different browsers may use default types for buttons */}
          <button type="submit" disabled={props.isSearching}>
            Search
          </button>
          {/* type="button" stops input validation message from being displayed (on Firefox) when randomize button is clicked without anything entered */}
          <button type="button" onClick={props.onRandomize} disabled={props.isSearching} className="randomize-button">
            Randomize
          </button>
        </div>
      </form>
    </>
  );
};

Example here: https://stackblitz.com/edit/react-db5ire 此处的示例: https : //stackblitz.com/edit/react-db5ire

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM