2017-08-16 53 views
0

我试图用新材料实现全局搜索ui下一个表组件,我有handleSearch方法,这个rec​​ive事件,并且比我使用regexp来检查event.target.value是否和表一样。但是当我在搜索中删除字符串时,列不会更新。它开始只搜索我开始输入。如何不仅被串在这种情况下全局表搜索反应

const columns = [ 
    { 
     dataKey: 'deviceType', 
     label:'Device Type', 
     numeric: false, 
    }, { 
     dataKey: 'deviceID', 
     label:'Device ID', 
     sortable: true, 
     numeric: true, 
     // cellRenderer: ({item, key}) => 
     //   <Button >Default</Button>, 
    }, { 
     ........ 
    }] 

const data = [ 
    { key: 1, deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'}, 
    { key: 2, deviceType: 'Tag', deviceID: 2, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'}, 
    {.......}, 
] 

class EnhancedTable extends Component { 
    state = { 
     selected: [], 
     data, 
     order: { 
      direction: 'asc', 
      by: 'deviceID', 
     }, 
     search: '', 
    } 

    handleSearch = event => { 
     debugger 
     const {data} = this.state 
     let filteredDatas = [] 
     filteredDatas = data.filter(e => { 
      let mathedItems = Object.values(e) 
      let returnedItems 
      mathedItems.forEach(e => { 
       const regex = new RegExp(event.target.value, 'gi') 
       if (typeof e == 'string') 
        returnedItems = e.match(regex) 
      }) 
      return returnedItems 
     }) 
     this.setState({data: filteredDatas, search: event.target.value}) 
    } 

    render =() => { 

     const {data, search} = this.state 

     return (
      <Paper> 
       <Table 
        data={data} 
        search={search} 
        onSearch={this.handleSearch} 
       /> 
      </Paper>) 
    } 
} 
export default EnhancedTable 
+0

按号码搜索,从我的理解你正在试图寻找数字。您可以将数字转换为JavaScript中的字符串。 –

+0

如果你说你希望每次删除一个字符都要搜索,或者如果你希望它在你删除搜索字段中的所有字符后更新表格,我有点困惑。如果是后者,似乎只需要更新正则表达式以检查空字符串,并且如果搜索字段为空,则返回所有项目。 – CaseyC

回答

0
fuzzyContains = (text, search) => { 
     debugger 
     if (!text) 
      return false 
     if (!search) 
      return true 

     search = search.toLowerCase() 
     text = text.toString().toLowerCase() 

     let previousLetterPosition = -1 

     return search.split('').every(s => { 
      debugger 
      previousLetterPosition = text.indexOf(s, previousLetterPosition + 1) 

      return previousLetterPosition !== -1 
     }) 
    } 

    handleSearch = search => { 
     const {data} = this.state 
     // debugger 
     let filteredData = data.filter(x => Object.keys(x).some(key => 
      // debugger 
      this.fuzzyContains(x[key], search) 
     )) 
     console.log(filteredData) 
     this.setState({filteredData, search}) 
    }