You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React猜国家测验:实现点击同一按钮依次显示提示的问题

解决依次展示提示的问题

你当前用布尔值show控制所有提示的显示/隐藏,自然会一点击就全出来。要实现依次展示,我们可以用提示层级状态记录当前应该显示到第几个提示,具体改法如下:

核心修改点

  • 把原来的show布尔状态换成hintLevel数值状态,初始设为0(表示还没显示任何提示)
  • 点击「Next Hint」时,让hintLevel递增,同时限制最大值(比如你有2个提示,就最多到2)
  • 根据hintLevel的数值,依次显示对应的提示
  • 点击「Next」切换国家时,重置hintLevel回到初始状态

修改后的完整代码

import React from 'react'
import "./Geography.css"
import {useState} from "react";
import country from "../Countries.json"

function Geography() {
  // 用hintLevel记录当前显示的提示层级,0=无提示,1=显示地区,2=显示地区+人口
  const [hintLevel, setHintLevel] = useState(0);
  const [image, setImage] = useState();
  const [area, setArea] = useState();
  const [population, setPopulation] = useState();
  const [countryList, setCountryList] = useState(country);

  
  const handleStart = () => {
      let random = Math.floor(Math.random() * country.length);
      setImage(countryList[random].image);
      setArea(countryList[random].area);
      setPopulation(countryList[random].population);
      // 切换国家时重置提示层级
      setHintLevel(0);
  }

  const handleNextHint = () => {
      // 最多显示2个提示,所以层级不超过2
      if (hintLevel < 2) {
          setHintLevel(prev => prev + 1);
      }
  }


  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={handleNextHint}>Next Hint</button>
        </div>
        <div className='pic'>
        <img src={image} />
        {/* 层级>=1时显示地区 */}
        {hintLevel >= 1 && <h1>{area}</h1>}
        {/* 层级>=2时显示人口 */}
        {hintLevel >= 2 && <h1>{population}</h1>}
      </div>
    </div>
  )
}

额外优化建议

  • 如果以后要加更多提示(比如首都、语言),只需要调整handleNextHint里的最大值,以及新增对应层级的显示判断即可
  • 可以给「Next Hint」按钮加禁用状态,当hintLevel达到最大值时按钮变灰不可点击,提升用户体验:
    <button 
      className='button__start' 
      onClick={handleNextHint}
      disabled={hintLevel >= 2}
    >Next Hint</button>
    

内容的提问来源于stack exchange,提问作者Brinda5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:34:54