基于Yes/No选择的React问答UI问题及回退需求求助
问题解决方案
一、修复Yes/No按钮无响应问题
按钮无响应核心是状态更新逻辑错误,需确保每次选择后正确更新当前问题和历史记录:
- 修正
handleAnswer函数,使用函数式更新获取最新状态:
const handleAnswer = (answer: 'yes' | 'no') => { setHistory(prev => [...prev, currentQuestion]); setCurrentQuestion(prev => { const nextId = prev[answer]; return questions.find(q => q.id === nextId) || prev; }); };
原代码若直接使用currentQuestion而非函数式更新,会因闭包捕获旧状态导致无法正确跳转下一个问题。
- 校验问题数据结构,确保
yes/no字段对应正确的下一个问题ID,示例结构:
const questions = [ { id: 1, text: '第一个问题?', yes: 2, no: 3 }, { id: 2, text: 'Yes跳转的问题?', yes: 4, no: 5 }, // 其他问题配置 ];
二、实现回退时的平滑滚动效果
- 给每个问题元素添加唯一ID用于定位:
<div key={currentQuestion.id} id={`question-${currentQuestion.id}`} className="question-container"> <p>{currentQuestion.text}</p> <button onClick={() => handleAnswer('yes')}>Yes</button> <button onClick={() => handleAnswer('no')}>No</button> </div>
- 实现回退函数,回退后触发平滑滚动:
const handleGoBack = () => { if (history.length === 0) return; const lastQuestion = history.pop(); setCurrentQuestion(lastQuestion); // 等待DOM更新后执行滚动 setTimeout(() => { const targetElement = document.getElementById(`question-${lastQuestion.id}`); targetElement?.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 0); };
- 添加回退按钮(仅当有历史记录时显示):
{history.length > 0 && ( <button onClick={handleGoBack} className="back-btn">回到上一题</button> )}
三、完整状态管理优化
使用函数式状态更新避免闭包陷阱,确保状态始终为最新值:
const [currentQuestion, setCurrentQuestion] = useState(questions[0]); const [history, setHistory] = useState<Question[]>([]); // 处理答案选择 const handleAnswer = (answer: 'yes' | 'no') => { setHistory(prevHistory => [...prevHistory, currentQuestion]); setCurrentQuestion(prevCurrent => { const nextQuestionId = prevCurrent[answer]; return questions.find(q => q.id === nextQuestionId) || prevCurrent; }); }; // 处理回退操作 const handleGoBack = () => { setHistory(prevHistory => { if (prevHistory.length === 0) return prevHistory; const updatedHistory = [...prevHistory]; const lastQuestion = updatedHistory.pop()!; setCurrentQuestion(lastQuestion); setTimeout(() => { const target = document.getElementById(`question-${lastQuestion.id}`); target?.scrollIntoView({ behavior: 'smooth' }); }, 0); return updatedHistory; }); };
修改后,按钮点击会正确跳转对应问题,回退时会平滑滚动到上一个问题的位置。
内容的提问来源于stack exchange,提问作者Calvin Care
相关产品推荐
相关产品推荐

