React电商网站按body lotion等类别实现产品过滤功能求助
实现React电商产品按类别过滤功能
核心思路
通过添加状态跟踪用户选中的产品类别,再根据该类别过滤产品数组,最终渲染匹配的产品。默认状态下显示所有产品。
具体修改步骤
- 添加类别状态:在组件中新增
selectedCategory状态,初始值设为null(代表显示所有产品)。 - 创建类别选择处理函数:编写
handleCategorySelect函数,更新selectedCategory状态,并关闭筛选菜单。 - 绑定筛选选项的点击事件:给每个筛选选项添加
onClick事件,传递对应的类别值(需和产品对象中的type字段严格匹配)。 - 过滤产品数组:根据
selectedCategory的值过滤u20arr,生成要渲染的产品列表。 - 添加选中样式:给当前选中的类别选项添加高亮样式,提升用户体验。
修改后的完整代码
import React, { useState } from 'react' import u20bg from "../assets/u20bg.png"; import "../styles/Under20.css"; import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbSeparator, } from '@chakra-ui/react' import { ChevronRightIcon } from '@chakra-ui/icons'; import { Link } from 'react-router-dom'; import filterBtn from "../assets/filterBtn.png"; import sortBtn from "../assets/sortBtn.png" const Under20 = () => { const [filter, setFilter] = useState(false); const [sort, setSort] = useState(false); // 跟踪选中的类别,初始为null表示显示所有产品 const [selectedCategory, setSelectedCategory] = useState(null); const filterShowHandler = () => { setFilter(!filter); } const toggleSortHandler = () => { setSort(!sort); } // 处理类别选择:更新状态并关闭筛选菜单 const handleCategorySelect = (category) => { setSelectedCategory(category); setFilter(false); } // 根据选中类别过滤产品数组 const filteredProducts = selectedCategory ? u20arr.filter(item => item.type === selectedCategory) : u20arr; const u20arr = [ // body wash { id: "43", name: "NATURAL LEMON BODY WASH", price: 18, type: "bodywash", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/NB_ScalpScrub200mlTube_200mL_02_large.jpg?v=1654006879", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/NO_Lists_for_Site-SIG_3ec6e6c0-aee5-483d-a6c9-e4abab736fd7_large.png?v=1654006879", stars: 4, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, { id: "44", name: "NATURAL STRAWBERRY BODY WASH", price: 15, type: "bodywash", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/NB_Leave-InConditioner_250ml_02_large.jpg?v=1654006878", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/NaturalBalance_7be6d9d2-0387-44f2-9949-b03a344fc044_large.jpg?v=1654006878", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, { id: "45", name: "NATURAL STRAWBERRY BODY WASH", price: 11, type: "bodywash", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/TravelPack2019_large.jpg?v=1652797301", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/TravelPack2019_large.jpg?v=1652797301", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, // body lotion { id: "46", name: "NATURAL BLUEBERRY BODY LOTION", price: 15, type: "bodyLotion", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/CreamyBodyWash500ml_large.jpg?v=1649168513", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/CreamyBodyFinal_large.jpg?v=1649168513", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, { id: "47", name: "NATURAL KIWI BODY LOTION", price: 19, type: "bodyLotion", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/Biomarine_Facial_Serum_02_FOR_WEB_large.jpg?v=1646144556", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/MicrosoftTeams-image_5_-SMALL_large.jpg?v=1646144556", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, { id: "48", name: "NATURAL AVACODA BODY LOTION", price: 14, type: "bodyLotion", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/Hydra_Eye_Gel_15ml_Tube_02_FOR_WEB_large.jpg?v=1646144555", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/MicrosoftTeams-image_5_-SMALL_533a775e-6e81-48de-bafa-6250300a0219_large.jpg?v=1646144555", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, // bodyScrub { id: "49", name: "EXFOLIATING JELLY SCRUB", price: 19, type: "bodyScrub", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/Brightening_JellyExfoliator125ml_02_large.jpg?v=1629210220", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/NO_Lists_for_Site_BRIGHTENING_451cbd3f-1e8b-446a-a45e-61cc31826f69_large.jpg?v=1629210220", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, { id: "50", name: "EXFOLIATING APPPLE SCRUB", price: 9, type: "bodyScrub", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/Brightening_IlluminatingMoisturiser60ml_02_large.jpg?v=1629210218", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/NO_Lists_for_Site_BRIGHTENING_cf1ff5a7-5a32-4bb0-a7ce-be69ccc9fcf0_large.jpg?v=1629210219", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, { id: "51", name: "EXFOLIATING KIWI SCRUB", price: 16, type: "bodyScrub", primaryImage: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/Bergamot_PachouliBodyWash500mL1000x1000x144_large.jpg?v=1637072534", hoverImg: "https://cdn.shopify.com/s/files/1/0081/7374/8305/products/Bergamot_PachouliBodyWashpumpLifestyle1000x1000x144_large.jpg?v=1637072534", stars: 5, descr: "Our Scalp Scrub removes product build up and impurities with a refreshing blend of Peppermint & Ginger Extract. " }, ] return ( <div className='u20MainParent'> <p className=' bg-white z-50 relative w100vw'> </p> <div className='u20Hold'> <img src={u20bg} className="u20Pic" /> </div> <div className='u20HeadingHold gap-20 justify-center relative flex flex-col'> <p className='u20Heading'> Under $20 </p> <p className='u20Desc'> Shop Sukin natural and vegan collection of skincare and hair care gifts under $20.</p> </div> <div className='u20BreadCrumbHold absolute text-sm'> <Breadcrumb spacing='8px' separator={<ChevronRightIcon />}> <BreadcrumbItem> <Link to={`/`}>Home</Link> </BreadcrumbItem> <BreadcrumbItem> <Link to={`/`}>Under 20</Link> </BreadcrumbItem> </Breadcrumb> </div> <div className='filterSortHold flex flex-row gap-8 absolute text-left'> <img src={filterBtn} className=" w-36 cursor-pointer scale" onClick={filterShowHandler} /> <img src={sortBtn} className=" w-36 cursor-pointer scale" onClick={toggleSortHandler} /> </div> <div className='filterOptionsHold relative'> {filter && <div className='flex rounded-xl gap-8 flex-col boxSh fof absolute '> {/* 添加点击事件和选中样式 */} <p className={`ml-10 cursor-pointer ${selectedCategory === 'bodyLotion' ? 'text-white' : ''}`} onClick={() => handleCategorySelect('bodyLotion')} > Body Lotion </p> <p className={`ml-10 cursor-pointer ${selectedCategory === 'bodyScrub' ? 'text-white' : ''}`} onClick={() => handleCategorySelect('bodyScrub')} > Body Scrub </p> <p className={`ml-10 cursor-pointer ${selectedCategory === 'bodywash' ? 'text-white' : ''}`} onClick={() => handleCategorySelect('bodywash')} > Body Wash </p> {/* 新增:显示全部选项 */} <p className={`ml-10 cursor-pointer ${selectedCategory === null ? 'text-white' : ''}`} onClick={() => handleCategorySelect(null)} > Show All </p> </div>} </div> <div> <div className='sortOptionsHold relative'> {sort && <div className='flex rounded-xl flex-col gap-7 boxSh2 fof absolute'> <p className='ml-20 cursor-pointer'> A - Z </p> <p className='ml-20 cursor-pointer'> Z - A </p> <p className='ml-10 cursor-pointer'> LOW TO HIGH </p> <p className='ml-10 cursor-pointer text-white'> HIGH TO LOW </p> </div>} </div> </div> {/* 渲染过滤后的产品 */} <div className='flex gap-20 flex-wrap relative top-96 justify-center text-center'> {filteredProducts.map((item) => { return (<div key={item.id}> <img src={item.primaryImage} className="w-32" /> <p> ${item.price} </p> <p>{item.name}</p> </div>) })} </div> </div> ) } export default Under20
关键说明
selectedCategory状态存储当前选中的类别,null代表显示所有产品。handleCategorySelect函数同步更新选中状态并关闭筛选面板,优化交互流程。filteredProducts通过filter方法动态生成匹配列表,默认返回原数组。- 复用原有
text-white类实现选中项高亮,保持样式一致性。 - 新增"Show All"选项,方便用户快速重置筛选状态。
内容的提问来源于stack exchange,提问作者Govind
相关产品推荐
相关产品推荐

