React实现二级联动Select菜单技术求助
解决方案:实现联动下拉菜单
首先先梳理你代码里的核心问题:变量名冲突、state逻辑混乱、下拉菜单的联动逻辑没建立起来。下面是修正后的完整代码,以及关键逻辑说明:
import { useState } from "react"; export default function Sort() { // 统一所有分类的数据结构,确保每个分类都有subsorter子选项数组 const categories = [ { label: "Price", subsorter: [ { sorter: "cheap to expensive" }, { sorter: "expensive to cheap" }, { sorter: "small to big" }, { sorter: "big to small" } ], }, { label: "Distance", subsorter: [ { sorter: "close to far" }, { sorter: "far to close" }, { sorter: "beach nearby" }, { sorter: "restaurant nearby" } ], }, { label: "Reviews", subsorter: [{ sorter: "lowest to highest" }] }, ]; // 保存第一个下拉菜单选中的分类 const [selectedCategory, setSelectedCategory] = useState(""); // 保存第二个下拉菜单选中的子选项 const [selectedSubOption, setSelectedSubOption] = useState(""); // 第一个菜单的选择事件:更新选中分类,同时重置子选项 const handleCategoryChange = (e) => { const categoryLabel = e.target.value; setSelectedCategory(categoryLabel); setSelectedSubOption(""); }; // 第二个菜单的选择事件:更新选中的子选项 const handleSubOptionChange = (e) => { setSelectedSubOption(e.target.value); }; // 根据选中的分类,获取对应的子选项数组 const currentSubOptions = selectedCategory ? categories.find(cat => cat.label === selectedCategory)?.subsorter || [] : []; return ( <div> <div className="flex"> <div>当前分类:{selectedCategory || "未选择"}</div> <select value={selectedCategory} onChange={handleCategoryChange}> <option value="">-- Filter --</option> {categories.map((category) => ( <option key={category.label} value={category.label}> {category.label} </option> ))} </select> </div> {/* 只有选中第一个分类后,才显示第二个下拉菜单 */} {selectedCategory && ( <div className="flex mt-4"> <div>当前子选项:{selectedSubOption || "未选择"}</div> <select value={selectedSubOption} onChange={handleSubOptionChange}> <option value="">-- By --</option> {currentSubOptions.map((sub, index) => ( <option key={index} value={sub.sorter}> {sub.sorter} </option> ))} </select> </div> )} </div> ); }
关键逻辑说明
- 统一数据结构:把
Reviews的结构改成和Price/Distance一致,都包含subsorter数组,避免处理特殊情况时出错。 - 分离状态管理:用两个独立的state分别保存第一个菜单的选中分类和第二个菜单的选中子选项,解决你之前变量名冲突、状态混乱的问题。
- 联动核心逻辑:
- 第一个菜单切换时,通过
find方法从分类数组中匹配选中的分类,取出对应的子选项数组 - 切换分类时重置子选项的选中状态,保证逻辑一致性
- 第一个菜单切换时,通过
- 条件渲染:只有选中第一个分类后才显示第二个菜单,符合你想要的“选择主分类后才出现子选项菜单”的效果。
内容的提问来源于stack exchange,提问作者Boq7
相关产品推荐
相关产品推荐

