反应-防止Form的onChange事件设置父状态,直到按下Enter键

时间:2019-09-25 07:25:22

标签: reactjs forms

子类Search的格式输入需要搜索一些字符串(例如:城市中的某些区域)。父组件App以状态存储搜索的值,以将其作为道具传递给另一种方法(Map组件)。

问题:当我开始在搜索表单中输入内容时,searchedValue会立即在父级中更新(由于onSearchedInputChange方法而无法使用)-

在更新父级状态之前,我如何让表单等到单击Enter之前?

App.js(父级)

class App extends React.Component {
  state = {
    searchedValue: "",
    searchedResponse: null
  };

handleSubmit = e => {
    e.preventDefault();
    ...
  };

  onSearchedInputChange = searchedValue => {
    this.setState({
      searchedValue: searchedValue
    });
  };

Search.js(子级)

class Search extends Component {
  handleSubmit = e => {
    this.props.handleSubmit(e);
  };
  // pass callback to parent with searched field
  handleSearch = e => {
    if (e.key === "Enter") {
      this.props.onSearchedInputChange(e.target.value);
    }
  };

  render() {
    const searchedValue = this.props.searchedValue;
    return (
      <div className="search">
        <Form onSubmit={this.handleSubmit}>
          <Form.Group controlId="searchForm" className="search-form">
            <InputGroup>
              <InputGroup.Prepend>
                <FontAwesomeIcon icon={faSearch} className="search-icon" />
              </InputGroup.Prepend>
              <Form.Control
                className="search-input"
                type="text"
                placeholder="Enter street or area..."
                value={searchedValue}
                name="search"
                onChange={this.handleSearch}
              />
            </InputGroup>
          </Form.Group>
        </Form>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

首先,您应该将输入值保存在子状态中,然后传递它,该句柄键事件以检查是否单击enter后,通过两种方式将子状态searchTerm传递到父类。因此,键入完毕后,文本将以searchTerm的状态保存,当您单击Enter并从prop调用函数并将searchTerm传递给父类时。

这是代码:

class Search extends Component {
  state = {
    searchTerm: ""
  };

  handleSubmit = e => {
    this.props.handleSubmit(e);
  };

  handleSearch = e => {
    this.setState({ searchTerm: e.target.value });
  };

  handleKeyPress = e => {
    if (e.key === "Enter") {
      this.props.onSearchedInputChange(this.state.searchTerm);
    }
  };

  render() {
    return (
      <div className="search">
        <Form onSubmit={this.handleSubmit}>
          <Form.Group controlId="searchForm" className="search-form">
            <InputGroup>
              <InputGroup.Prepend>
                <FontAwesomeIcon icon={faSearch} className="search-icon" />
              </InputGroup.Prepend>
              <Form.Control
                className="search-input"
                type="text"
                placeholder="Enter street or area..."
                value={this.state.searchTerm}
                name="search"
                onChange={this.handleSearch}
                onKeyPress={this.handleKeyPress.bind(this)}
              />
            </InputGroup>
          </Form.Group>
        </Form>
      </div>
    );
  }
}