如何优化问卷场景下按钮点击后的值获取效率与实现方式?
优化方案
1. 抽离选项配置,循环渲染按钮
把重复的按钮配置抽成数组,通过map循环生成按钮,彻底消除冗余代码:
// 定义选项配置数组 const ratingOptions = [ { value: "1", label: "Molto poco" }, { value: "2", label: "Abbastanza" }, { value: "3", label: "Importanti" }, { value: "4", label: "Fondamentali" }, ]; // 组件内渲染部分 <div className="mt-4 d-grid gap-2 col-8 mx-auto"> {ratingOptions.map((option) => ( <button key={option.value} className="btn btn-light shadow-sm btn-lg fw-normal" type="submit" value={option.value} onClick={handleAnswers} > {option.label} </button> ))} </div>
2. 简化handleAnswers函数
原函数中传递的第二个参数未被使用,直接移除即可,同时用函数式更新优化状态设置(避免依赖旧状态值的潜在问题):
const handleAnswers = (e) => { e.preventDefault(); const questionResponse = e.target.value; const questionId = currentQuestionCounter; // 函数式更新,确保获取最新的answers状态 setAnswers(prevAnswers => [...prevAnswers, { questionId, questionResponse }]); nextQuestion(); };
3. 可选进阶优化
- 添加选中状态高亮:如果需要让用户直观看到当前选中的选项,可以新增状态记录选择,动态修改按钮样式:
// 新增状态存储当前选择 const [currentSelection, setCurrentSelection] = useState(""); // 修改按钮className,选中时切换样式 className={`btn ${currentSelection === option.value ? 'btn-primary' : 'btn-light'} shadow-sm btn-lg fw-normal`} onClick={(e) => { setCurrentSelection(option.value); handleAnswers(e); }} - 缓存事件处理函数:如果组件频繁渲染,用
useCallback缓存handleAnswers,避免不必要的子组件重渲染:const handleAnswers = useCallback((e) => { e.preventDefault(); const questionResponse = e.target.value; const questionId = currentQuestionCounter; setAnswers(prevAnswers => [...prevAnswers, { questionId, questionResponse }]); nextQuestion(); }, [currentQuestionCounter, nextQuestion]);
内容的提问来源于stack exchange,提问作者habby
相关产品推荐
相关产品推荐

