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

时间:2019-04-22 00:37:52

标签: javascript reactjs

在提交值并使用该值执行搜索之后,我想清除搜索输入。在类似的问题中,建议将输入值的状态设置为'',但是我认为这是我尝试的方法,它什么也没做。

我的应用程序中只有一个父级和子级组件。父组件具有一种用于搜索笑话(searchJokes)的方法,并且作为道具以与onFormSubmit={this.searchJokes}组件实例中的子组件不同的名称向下传递。在子组件中,当用户向搜索输入中输入内容时,其event.target.valueonChange={e => props.onInputChange(e.target.value)}一起传递给父道具中的onSearchChange方法,并且该值用于更新{ {1}}。

我在searchJokes方法的末尾添加了searchTerm,该方法根据搜索项来进行搜索,如下面的父组件代码所示。

父组件:

searchTerm: ''

子组件:

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>
    );
  };
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

基本上,您需要以组件的状态存储输入值。调用onSubmit时,我们应该将该值恢复为空字符串。

具有一些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>
    </>
  );
};

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