【问题标题】:How do I create a search filter for a JSON datatable in React?如何在 React 中为 JSON 数据表创建搜索过滤器?
【发布时间】:2021-04-26 08:30:18
【问题描述】:

我一直在尝试通过按数据头的值过滤数据来实现 JSON 数据表的搜索过滤器...

这是输入字段

 <input type= "text" placeholder="Search..." value={search} onChange={(e) => 
 {setSearch(e.target.value)}} />

下面是数据表..

<table cellSpacing="40" cellPadding="20" >
            <thead>
                <tr>
                <th>#ID</th>
                <th>Name</th>
                <th>Gender</th>
                <th>LGA</th>
                <th>WARD</th>
                </tr>
            </thead>
            <tbody>
    {person.map(record =>(
        <tr key = {record.id}>
        <td>{record.id}</td>
        <td> <Link to={`/beneficiary/${record.full_name}`} >
         {record.full_name}</Link></td>
         <td>{record.gender}</td>
         <td>{record.lga}</td>
         <td> {record.ward} </td>
        </tr>     
    ))}
    
</tbody>
</table>
    
}

我如何用数据表包装输入字段,以便能够通过其数据头的值获取数据。说,性别的标题..我想得到男性的结果。等

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    根据您的描述,您需要将过滤规则添加到person.map(...),即您需要使用person.filter(somefilterfunction).map(record =&gt; (。所以现在的问题变成了如何对somefilterfunction 进行编程以满足您的需求,例如您想过滤男性,然后使用

    (person) => {
        if (person.gender === search) {
            return person;
        }
    }
    

    这里的search应该是你的状态(我猜你正在使用React hooks),其他过滤规则也可以类似地实现。


    Modern React 也支持useMemo,它可以作为过滤数据的缓存,这可能会有更好的性能。您可以通过look at the official document 或谷歌来深入了解它。

    【讨论】:

      【解决方案2】:

      先过滤数据

             {person.filter((e) => ['name', 'descr']
             .some((property)=> e[property].toLowerCase()
             .includes(search.toLowerCase())))
             .map(record =>(
                  <tr key = {record.id}>
                  <td>{record.id}</td>
                  <td> <Link to={`/beneficiary/${record.full_name}`} >
                   {record.full_name}</Link></td>
                   <td>{record.gender}</td>
                   <td>{record.lga}</td>
                   <td> {record.ward} </td>
                  </tr>     
              ))}
      

      【讨论】:

        猜你喜欢
        • 2020-11-22
        • 2018-05-09
        • 2017-06-24
        • 1970-01-01
        • 2021-02-12
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        相关资源
        最近更新 更多