React同数据源多下拉框实现选择值独立不联动问题咨询
核心问题说明
你当前所有下拉框都绑定了同一个bundle状态变量,任意下拉框修改状态都会触发所有下拉框同步更新,要实现独立选中需要为每个下拉框单独存储选中值。
修复后的完整代码
import React, { useState } from "react"; const options = [ { label: "巴西莓", value: "acaiberry", color: "#FF4D4D", quantity: 1, price: 20, // 实际使用时请补充对应图片地址 image: "" }, { label: "血橙", value: "bloodorange", color: "#FF4D4D", quantity: 1, price: 32, image: "" }, { label: "蜂蜜姜柠", value: "honeyginger", quantity: 1, color: "#FF4D4D", price: 17, image: "" } ]; // 下拉框数量可根据需求灵活调整 const SELECT_COUNT = 2; const RandomizerComponent = () => { // 状态改为数组,每个元素对应一个下拉框的选中值 const [bundleList, setBundleList] = useState(new Array(SELECT_COUNT).fill("acaiberry")); // 接收下拉框索引参数,仅修改对应位置的状态 const handleChange = (index, e) => { const newBundleList = [...bundleList]; newBundleList[index] = e.target.value; setBundleList(newBundleList); }; const spin = () => { randomItems(); }; const randomItems = () => { const newBundleList = [...bundleList]; // 为每个下拉框生成独立的随机选中值 for (let i = 0; i < SELECT_COUNT; i++) { const randomIndex = Math.floor(Math.random() * options.length); newBundleList[i] = options[randomIndex].value; } setBundleList(newBundleList); }; const quantityOfSomething = new Array(SELECT_COUNT).fill(options); return ( <div> <h1 style={{textAlign: "center"}}>确认选择</h1> <div className="select-container"> <div className="select-Wrapper"> {quantityOfSomething.map((item, index) => ( <div key={`select-${index}`}> <select value={bundleList[index]} onChange={(e) => handleChange(index, e)} className="selectList" > {item.map((option, optIndex) => ( <option key={optIndex} value={option.value}> {option.label} </option> ))} </select> <div> {item .filter((option) => option.value === bundleList[index]) .map((filteredBundle, idx) => ( <div className="image-wrapper" key={idx}> <img src={filteredBundle.image} alt={filteredBundle.label} /> </div> ))} </div> </div> ))} </div> <div> <button onClick={spin} className="spin-btn"> 随机选择 </button> </div> </div> </div> ); }; export default RandomizerComponent;
关键改动说明
- 状态结构调整:将原本单值的
bundle状态修改为数组bundleList,数组长度和下拉框数量一致,每个位置存储对应下拉框的选中值,实现各下拉框状态隔离 - 交互逻辑调整:修改
handleChange方法新增索引入参,修改时仅更新对应索引位置的状态值,避免影响其他下拉框 - 随机逻辑调整:点击随机按钮时遍历所有下拉框,为每个下拉框单独生成随机选中值
- 渲染逻辑优化:修复了原有列表key重复的问题,过滤展示选中项对应的图片时,使用当前索引的选中值做匹配
内容的提问来源于stack exchange,提问作者hamza liaqat
相关产品推荐
相关产品推荐

