清除空输入中的数据-React.js

时间:2018-09-16 15:07:59

标签: javascript reactjs

我试图找到一种方法来检查是否清除了我的输入以清除数据。

我用于此检查的逻辑是if (searchTerm.length === 0)清除输入...我也尝试过if (searchTerm === ''),但它们不起作用。这些逻辑检查的作用是,当清除输入并在字符串长度为0时应添加1个字符(应为1时)时触发事件?

当我console.log输入字符串长度时,我得到0代表1个字符,1代表2个字符,当我完全清除输入时,我得到1代表0个字符。 / p>

检查已清除的输入值的正确方法是什么?

这是我的逻辑:

class SearchBar extends Component {
  state = {
    searchTerm: '',
    error: null
  }

  handleChange = e => {
    const { searchTerm } = this.state

    this.setState({ searchTerm: e.target.value })

    if (searchTerm.trim() === '') {
      this.props.resetSearch()
    }
  }

  render() {
    const { searchTerm, error } = this.state

    return (
      <div className="input-container">
        { error && <p className="invalid">Please Enter Something</p> }
        <input 
          type="text"
          placeholder="search for a repo..."
          value={searchTerm}
          onChange={e => this.handleChange(e)}
          onKeyPress={e => e.key === 'Enter' && this.findRepos(e)}
        />
        <button 
          type="submit" 
          onClick={e => this.findRepos(e)}>
          Search
        </button>
      </div>
    )
  }
}

export default connect(null, { fetchRepos, resetSearch })(SearchBar)

1 个答案:

答案 0 :(得分:2)

@using (Html.BeginForm()) {
    <p>Do you like pizza?
        @Html.DropDownListFor(x => x.likesPizza, new[] {
            new SelectListItem() {Text = "Yes", Value = bool.TrueString},
            new SelectListItem() {Text = "No", Value = bool.FalseString}
        }, "Choose an option") 
    </p>
    <input type = "submit" value = "Submit my answer" />
} 

您正在检查以前的状态,而不是当前输入值。您的代码应为

handleChange = e => {
  const { searchTerm } = this.state

  this.setState({ searchTerm: e.target.value })

  if (searchTerm.trim() === '') {
    this.props.resetSearch()
  }
}