微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在reactJs中为表内容创建搜索功能

如何解决在reactJs中为表内容创建搜索功能

我正在尝试为表格内容构建搜索和排序功能。我不想使用包,因为我正在尝试学习并查看反应搜索的工作方式。我有以下内容可以从有效载荷中加载内容

import React,{useState,useEffect} from 'react'
import '../css/about.css'; 
import Pagination from '../components/Pagination'
function About() {
    const [userData,setUserData] = useState([]);
    const [loading,setLoading] = useState(false);
    const [currentPage,setCurrentPage] = useState(1);
    const [postsPerPage,setPostsPerPage] = useState(5);
    const [search,setSearch] = useState("");

    async function getData() 
        {
           let response = await fetch('https://api.github.com/users');
           let data = await response.json();
            // setUserData(data)
            return data;
        }
        //call getData function
        getData()
        .then(data => console.log(data)
        );//
    useEffect(() => {
        setLoading(true)
        getData()
        .then(
           data => {
               setUserData(data) }
        )
        .catch(error => {
            console.log(error);
          })
    },[])


      // Get current posts
      const indexOfLastPost = currentPage * postsPerPage;
      const indexOfFirstPost =  indexOfLastPost - postsPerPage;
      const currentPosts = userData.slice(indexOfFirstPost,indexOfLastPost);

      // changw page 
      const paginate = (pageNumber) => setCurrentPage(pageNumber);

      // Search Table 
      const handleFilterChange = e => {
          const value = e.target.value || undefined;
          if( search !== "" && userData.login.indexOf(search.toLowerCase()) === -1 ) {
            return null;
        }
            setSearch(value)
      }


    return (
        <div className="container">

                 <div>
                     <input value={search}
                     onChange={handleFilterChange}
                     placeholder={"Search"}

                     />
                     <table>
                         <thead>
                         <tr>
                             <td>id</td>
                             <td>avatar_url</td>
                             <td>events_url</td>
                             <td>followers_url</td>
                             <td>following_url</td>
                             <td>gists_url</td>
                             <td>gravatar_id</td>
                             <td>html_url</td>
                             <td>login</td>
                             <td>node_id</td>
                             <td>organizations_url</td>
                             <td>received_events_url</td>
                             <td>repos_url</td>
                             <td>site_admin</td>
                             <td>starred_url</td>
                             <td>subscriptions_url</td>
                             <td>type</td>
                             <td>url</td>
                         </tr>
                         </thead>
                         <tbody>
                         { 
             currentPosts.map((item,index) => (
                         <tr  key={index}>
                             <td>{item.id}</td>
                            <td>{item.avatar_url}</td>
                             <td>{item.events_url}</td>
                             <td>{item.followers_url}</td>
                             <td>{item.following_url}</td>
                             <td>{item.gists_url}</td>
                             <td>{item.gravatar_id}</td>
                            <td>{item.html_url}</td>
                             <td>{item.login}</td>
                             <td>{item.node_id}</td>
                             <td>{item.organizations_url}</td>
                             <td>{item.received_events_url}</td>
                             <td>{item.repos_url}</td>
                             <td>{item.site_admin}</td>
                             <td>{item.starred_url}</td>
                             <td>{item.subscriptions_url}</td>
                             <td>{item.type}</td>
                             <td>{item.url}</td>
                         </tr>
                          ))
                        }
                         </tbody>
                     </table>
                     <Pagination postsPerPage={postsPerPage} totalPosts={userData.length} paginate={paginate} />
                 </div>
            
                 
        </div>
    )
}

export default About

下面列出了分页代码

import React from 'react'

 const Pagination = ({ postsPerPage,totalPosts,paginate }) => {
     const pageNumbers = [];
     for(let i = 1; i <= Math.ceil(totalPosts / postsPerPage);  i++) {
        pageNumbers.push(i);
     } 
    return (
        <div>
            <ul className="pagination">
                {pageNumbers.map(number => (
                    <li key={number} className="page-item">
                            <a onClick={() => paginate(number)} 
                            href="#" className="page-link">
                                {number}
                            </a>
                    </li>
                ))}

            </ul>
        </div>
    )
}
export default Pagination

我认为是因为我在tbody中使用了.map,并且搜索不会影响内容。尽管我没有错误,但是搜索参数什么也没显示

解决方法

我注意到您没有创建处理搜索的功能。您可以使用这种通用方法来搜索行和列,并匹配大小写。

function DataSearch(rows) {
        const columns = rows[0] && Object.keys(rows[0]);
        return rows.filter((row) =>
        columns.some((column) => row[column].toString().toLowerCase().indexOf(search.toLowerCase()) > -1)
        );
    }

实例化功能

const  searchPosts = DataSearch(currentPosts);

在tbody中的.map函数上使用searchPosts。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。