在Reactjs中,搜索输入和分页通常是通过以下步骤来实现的:
以下是一个示例代码,演示了如何在Reactjs中实现搜索输入和分页功能:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const SearchPage = () => {
const [searchKeyword, setSearchKeyword] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const [searchResults, setSearchResults] = useState([]);
useEffect(() => {
fetchData();
}, [searchKeyword, currentPage]);
const fetchData = async () => {
try {
const response = await axios.get(`/api/search?q=${searchKeyword}&page=${currentPage}`);
setSearchResults(response.data.results);
} catch (error) {
console.error(error);
}
};
const handleSearchInputChange = (event) => {
setSearchKeyword(event.target.value);
};
const handlePageChange = (page) => {
setCurrentPage(page);
};
return (
<div>
<input type="text" value={searchKeyword} onChange={handleSearchInputChange} />
<ul>
{searchResults.map((result) => (
<li key={result.id}>{result.title}</li>
))}
</ul>
<Pagination currentPage={currentPage} onPageChange={handlePageChange} />
</div>
);
};
const Pagination = ({ currentPage, onPageChange }) => {
const handlePageClick = (page) => {
onPageChange(page);
};
return (
<div>
<button onClick={() => handlePageClick(currentPage - 1)}>Previous</button>
<span>{currentPage}</span>
<button onClick={() => handlePageClick(currentPage + 1)}>Next</button>
</div>
);
};
export default SearchPage;
在上述示例中,父组件SearchPage
包含了搜索输入框、搜索结果列表和分页组件。当搜索输入框的内容发生变化时,handleSearchInputChange
函数会更新searchKeyword
的状态。当分页按钮被点击时,handlePageChange
函数会更新currentPage
的状态。useEffect
钩子函数会监视searchKeyword
和currentPage
的变化,并在变化时调用fetchData
函数来获取数据。获取到的数据会存储在searchResults
的状态中,并通过列表组件展示出来。分页组件Pagination
接收当前页数和页数变化的回调函数,并根据当前页数和点击事件来更新页数。
这个示例中使用了Axios库来发送异步请求,你可以根据实际情况选择其他库或自行实现。另外,需要注意的是,示例中的API请求路径和数据结构是假设的,你需要根据实际情况进行修改。
推荐的腾讯云相关产品和产品介绍链接地址:
请注意,以上推荐的腾讯云产品仅供参考,具体选择应根据实际需求和项目要求进行评估。
领取专属 10元无门槛券
手把手带您无忧上云