我正在使用react-table作为数据网格。我正在实现基于表的搜索过滤。过滤似乎不起作用,因此返回空结果。我没有错。
有人可以帮忙吗?
我们将不胜感激
let data =[ {id: 1, val1: "45GFSDSD", val2: "AKFHFDH83E3HHYE"},
{id: 2, val1: "46FDGDGDGDG", val2: "AKFHFDH83E3HFGD"},
{id: 3, val1: "56FDGGFGF", val2: "AERTFDH83E3HHYD"}
]
import * as React from 'react';
import ReactTable from 'react-table';
class MyTable extends React.Component {
constructor () {
super();
this.state = {
data: data, // data from API, structure has been shown above
search: ''
}
}
render () {
let data = this.state.data
if (this.state.search)
{
data = data.filter((value) => {
return value.val1.includes(search)||value.val2.includes(search)|| String(value.id).includes(search)
})
}
return (
<div>
Search:
<input value={this.state.search} onChange={e => this.setState({search: e.target.value})} />
<ReactTable data={data} columns={columns} />//column object
</div>
)
}
}
答案 0 :(得分:1)
您需要有两个数组,一个数组用于存储来自api的数据,另一个数组用于过滤的数据。您的状态将是这样。
//on first load both arrays will have the same data
state = {
data: [
{ id: 1, val1: "45GFSDSD", val2: "AKFHFDH83E3HHYE" },
{ id: 2, val1: "46FDGDGDGDG", val2: "AKFHFDH83E3HFGD" },
{ id: 3, val1: "56FDGGFGF", val2: "AERTFDH83E3HHYD" }
],
filteredData: [
{ id: 1, val1: "45GFSDSD", val2: "AKFHFDH83E3HHYE" },
{ id: 2, val1: "46FDGDGDGDG", val2: "AKFHFDH83E3HFGD" },
{ id: 3, val1: "56FDGGFGF", val2: "AERTFDH83E3HHYD" }
]
};
然后,当输入中的文本更改时,您将需要一个用于过滤数据的功能
handleSearch = event => {
const search = event.target.value.toLowerCase();
this.setState({
filteredData: this.state.data.filter(
item =>
(item.val1 && item.val1.toLowerCase().includes(search)) ||
(item.val2 && item.val2.toLowerCase().includes(search))
)
});
};
您的输入
<input
type="text"
value={this.state.value}
onChange={this.handleSearch}/>
表从filteredData数组获取数据
<ReactTable data={this.state.filteredData} columns={columns} />