簡體   English   中英

清除空輸入中的數據-React.js

[英]Clear data on empty input - React.js

我試圖找到一種方法來檢查是否清除了我的輸入以清除數據。

我用於此檢查的邏輯是if (searchTerm.length === 0)清除輸入...我也嘗試過if (searchTerm === '')但它們不起作用。 這些邏輯檢查的作用是,當清除輸入並在字符串長度為0時應添加1個字符(應為1)時觸發該事件?

當我CONSOLE.LOG我的輸入字符串的長度,我得到0為1個字符, 1 2個字符,當我徹底清除輸入我得到1 0個字符。

檢查已清除的輸入值的正確方法是什么?

這是我的邏輯:

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)
handleChange = e => {
  const { searchTerm } = this.state

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

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

您正在檢查以前的狀態,而不是當前輸入值。 您的代碼應為

handleChange = e => {
  const searchTerm = e.target.value;

  this.setState({ searchTerm: searchTerm })

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM