【问题标题】:How to clear input after form submit (React)表单提交后如何清除输入(React)
【发布时间】:2019-04-22 00:37:51
【问题描述】:

在提交值并使用该值执行搜索后,我想清除一个搜索输入。在类似的问题中,建议将输入值的状态设置为'',但我认为这就是我尝试过的,它没有做任何事情。

我的应用中只有一个父子组件。父组件有一个搜索笑话的方法(searchJokes),它作为一个具有不同名称的prop传递给组件实例中onFormSubmit={this.searchJokes}的子组件。在子组件中,当用户在搜索输入中输入内容时,其event.target.value 与父prop 中的onSearchChange 方法对应的onChange={e => props.onInputChange(e.target.value)} 一起传递,该值用于更新searchTerm 的状态。

我在 searchJokes 方法的末尾添加了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>
    );
  };
}

子组件:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要将您的 searchTerm 传递给 RetrievalForm 并在该输入中设置 value={searchTerm} 以便它的值将绑定到该状态。

    【讨论】:

      【解决方案2】:

      基本上,您需要将输入值存储在组件的状态中。当调用 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

      【讨论】:

        猜你喜欢
        • 2018-03-14
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 2020-07-14
        相关资源
        最近更新 更多