搜索过滤器输入ReactJS

时间:2018-12-05 14:09:07

标签: reactjs

我上课是Compopnent:

  state = {
   names: ['first', 'second']
  };

  updateSearch = (event) => {
   let updatedList = this.state.names;
    updatedList = updatedList.filter(name=> {
     return name.toLowerCase().search(
       event.target.value.toLowerCase()) !== -1;
     })
   this.setState({names: updatedList});
  }


 render() {
  const names = this.state.names.map((name) => { return (
    <div key={name}>
      <span>{name}</span>
    </div>
  )})
  return (
   <div>
    <input 
      placeholder="Search" 
      type="text" 
      onChange={this.updateSearch} />
        {names}
   </div>
    )
}

当我输入一些与该名称一致的文本时,search在起作用,并且仅显示该名称,但是当我从input删除文本时,所有名称应显示回来,但它们不会显示t(仅显示先前搜索的名称)。为什么?

感谢提前答复!

1 个答案:

答案 0 :(得分:1)

  Add one more val in state as initialName and in updateSearch set updateSearch value 
with initalNames.
Try This.
 state = {
   names: ['first', 'second'],
   intiailNames:['first','second']
 };

updateSearch = (event) => {
 let updatedList = this.state.intiailNames;
 updatedList = updatedList.filter(name=> {
 return name.toLowerCase().search(
   event.target.value.toLowerCase()) !== -1;
 })
this.setState({names: updatedList});
 }