如何在ReactJS中过滤onChange?

时间:2018-04-10 19:49:15

标签: javascript reactjs

我有以下代码filterNames()

filterNames() {
    const { peoples } = this.state;
    this.setState({
      filtered: peoples.filter(item => item.name.includes(this.state.input)),
      currentPage:0
    });
    console.log(this.state.filtered)
} 

单击此按钮时会过滤

按钮:

<button className='search' onClick={this.filterNames}>
    Search
</button>

输入:

<input type="text" onChange={ this.getValueInput }></input>

我希望它在输入时输入字母'a'的位置,过滤。

恢复:我想在不点击按钮的情况下进行过滤,就像输入输入一样。

我的代码全部:

class Pagination extends React.Component {
  constructor() {
    super();
         
    const peoples = [
      {id:0, name:"Jean"}, 
      {id:1, name:"Jaquinha"}, 
      {id:2, name:"Ricardo"}, 
      {id:3, name:"JaCA"}, 
      {id:4, name:"Letiiicia"}, 
      {id:5, name:"Dai"}, 
      {id:6, name:"Da iIIane"}, 
      {id:7, name:"Tamy"}, 
      {id:8, name:"Tamyresss"},
      {id:9, name:"Tamyres"}, 
      {id:10, name:"Abeu"}, 
      {id:11, name:"Abellll"}
    ];
    
    this.state = {
      elementsPerPage:3,
      currentPage:0,
      peoples,
      input: "",
      filtered: peoples,
    };

    this.nextPage = this.nextPage.bind(this);
    this.previousPage = this.previousPage.bind(this);
    this.filterNames = this.filterNames.bind(this);
    this.getValueInput = this.getValueInput.bind(this);
  } 
  
  getValueInput (value) {
    this.setState({ input: value.target.value });
  }
    
  filterNames() {
    const { peoples } = this.state;
    this.setState({
      filtered: peoples.filter(item => item.name.includes(this.state.input)),
      currentPage:0
    });
    console.log(this.state.filtered)
  } 
  
  elementsOnScreen() {
    const { elementsPerPage, currentPage, filtered } = this.state;
    return filtered
      .map((item) => <li key={item.id}> {item.name} <button onClick={() => this.remove(item.name)}> Delete </button> </li>)
      .slice(currentPage*elementsPerPage, currentPage*elementsPerPage + elementsPerPage);
    
    if (this.state.filtered.length < 1) {
      this.setState({currentPage: this.state.currentPage - 1})
    }
  }

  remove = (id) => {
    console.log(this.state.filtered.length)
    if (this.state.filtered.length < 0) {
       this.setState({currentPange: this.state.currenPage - 1})
    }
    this.setState({filtered: this.state.filtered.filter(item => item.name !== id) })
  }
  
  nextPage() {
    console.log(this.state.filtered)

    const {elementsPerPage, currentPage, filtered} = this.state;
    
    if ((currentPage+1) * elementsPerPage < filtered.length){
      this.setState({ currentPage: this.state.currentPage + 1 });
    }
  }
  
  previousPage () {
    const { currentPage } = this.state;
    if(currentPage - 1 >= 0){
      this.setState({ currentPage: this.state.currentPage - 1 });
    }
  }

  render() {
    return (
      <div>
        <input type="text" onChange={ this.getValueInput }></input>
        <button className='search' onClick={this.filterNames}> Search </button>
        <button onClick={this.previousPage}> Previous </button>
        <button onClick={this.nextPage}> Next </button>
        <h3>Current Page: {this.state.currentPage}</h3>
        <ul>Names: {this.elementsOnScreen()}</ul>
      </div>
    );
  }
}


ReactDOM.render(
  <Pagination/>,
  document.getElementById('root')
)
<div id="root"></div>

1 个答案:

答案 0 :(得分:2)

您可以更新 getValueInput 来处理过滤。

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int month = 7;
        int date = 20;
        boolean check = isValidDate(month, date);
        System.out.println(check);
    }

    public static boolean isValidDate(int month, int day) {
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
            if (day < 32) {
                return true;
            }
        if (month == 4||month == 6 || month == 9|| month ==11 )
            if(day < 31)
            return true;
       if (month== 2) 
           if(day < 29)
        }
        return false;
    }
    {
   public static String findSeason(int month, int day) {
        return "invalid date";
        switch:(month) {

           case 1: // january same season
           case 2: // february
               return "winter";
           case 3: // march
// season changes
           return (day <= 20? "winter" : "spring");
           case 4:// april
           case 5: //may
               return "spring";
            case 6: // june 
//season changes
           return (day <=20? "spring" : "summer");
           case 7: // july
           case 8: // august
               return"autumn";
           case 9: // september
           return (day <=20? "summer" : "autumn");
           case 10: // october
           case 11: // november
           return (day <=20? "autumn" : "winter");
           case 12: //december
    }
   return "invalidDate";}
  

注意:您必须传入 inputValue ,因为 React 会批量处理 setState 。如果您检查,即使在调用setState之后, this.state.input 仍将是您之前的值。这就是为什么你必须依赖 filterNames

中的 evt.target.value 的原因

Dan在这里给出了一个很好的简要解释,说明React如何批量调用setState。 https://github.com/facebook/react/issues/10231#issuecomment-316644950