React地理测验:实现点击按钮依次触发提示显示功能
解决方案
核心思路是用一个状态变量跟踪当前的提示展示阶段,每次点击"Next Hint"按钮时,根据当前阶段逐步展示对应的提示信息,同时避免直接操作DOM,改用React状态驱动视图渲染。
具体修改步骤:
新增提示阶段状态
添加hintStage状态,用来标记当前已展示到第几个提示:- 0:未展示任何提示
- 1:已展示面积提示
- 2:已展示人口提示
重置提示状态
在切换新国家时,重置hintStage为0,确保每次新测验的提示从第一步开始。修改提示触发逻辑
更新handleHint函数,根据当前hintStage的值,决定展示下一个提示,并更新阶段状态。用状态控制视图渲染
不再直接操作DOM元素的innerHTML,而是通过状态值来控制对应提示内容的显示,符合React的数据流理念。
修改后的完整代码:
import { useState } from "react"; import country from "../Countries.json" function Geography() { const [image, setImage] = useState(); const [currentArea, setCurrentArea] = useState(""); const [currentPopulation, setCurrentPopulation] = useState(""); // 新增提示阶段状态,0=无提示,1=显示面积,2=显示人口 const [hintStage, setHintStage] = useState(0); const handleStart = () => { const randomIndex = Math.floor(Math.random() * country.length); const selectedCountry = country[randomIndex]; setImage(selectedCountry.image); setCurrentArea(selectedCountry.area); setCurrentPopulation(selectedCountry.population); // 重置提示阶段,回到初始状态 setHintStage(0); }; const handleHint = () => { // 根据当前阶段推进提示进度 if (hintStage === 0) { setHintStage(1); } else if (hintStage === 1) { setHintStage(2); } // 阶段到2后,再点击可选择不做操作,或重置阶段,按需调整 }; return ( <div className='geo'> <h1>Guess the Country</h1> <div className='button'> <button className='button__start' onClick={handleStart}>Next</button> <button className='button__start' onClick={handleHint}>Next Hint</button> </div> <div className='pic'> {image && <img src={image} alt="Country flag" />} {/* 根据hintStage控制提示显示 */} {hintStage >= 1 && <h1>{currentArea}</h1>} {hintStage >= 2 && <h1>{currentPopulation}</h1>} </div> </div> ); } export default Geography;
关键改动说明:
- 移除了直接操作DOM的代码,改用React状态控制视图,避免违背React的设计模式。
- 用
hintStage状态实现分步提示,每次点击"Next Hint"只推进一个阶段,确保提示依次显示。 - 优化了变量命名,提升代码可读性。
- 为图片添加
alt属性,符合网页无障碍标准。
内容的提问来源于stack exchange,提问作者Brinda5
相关产品推荐
相关产品推荐

