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

React按钮aria-pressed状态问题:点击需重置所有按钮并激活当前按钮

问题分析

你当前的问题核心在于**suggestion.id可能不存在**,导致所有按钮的aria-pressed判断条件都为undefined === undefined,从而全部变为true。你的状态逻辑本身是合理的(用单个状态值记录当前选中的按钮标识),但标识的取值出错了。

解决方案

根据你的suggestions数组结构,分两种场景处理:

场景1:suggestions是字符串数组(如["苹果", "香蕉", "橙子"])

此时每个suggestion没有id属性,直接用suggestion本身作为唯一标识即可:

import React, { useState} from 'react'
import './suggestedSearches.scss'

const SuggestedSearches = ({ suggestedSearches, query, setQuery, seachButtonRef }) => {
  const { label, suggestions } = suggestedSearches
  // 初始值设为null,表示无选中按钮
  const [pressedKey, setPressedKey] = useState(null);

  const handleOnClick = (event) => {
    const buttonValue = event.currentTarget.value
    setQuery(buttonValue)
    setTimeout(() => seachButtonRef.current.click())
    // 用当前按钮的value作为选中标识
    setPressedKey(buttonValue)
  }

  return (
    <>
      {(suggestions && suggestions.length > 0) &&
        <div className='suggested-searches'>
          <h3 className='label'>{label}</h3>
          <div className='suggested-buttons'>
            {suggestions.map((suggestion) => (
              <button
                key={suggestion}
                value={suggestion}
                className={`suggested-button ${suggestion === query ? 'selected' : ''}`}
                onClick={handleOnClick}
                // 对比当前suggestion是否等于选中标识
                aria-pressed={pressedKey === suggestion}
              >
                {suggestion}
              </button>
            ))}
          </div>
        </div>}
    </>
  )
}

export default SuggestedSearches

场景2:suggestions是对象数组(如[{id: 1, text: "苹果"}, {id:2, text:"香蕉"}])

如果是对象数组,确保每个元素有唯一id,同时调整按钮的value、显示内容和标识判断:

import React, { useState} from 'react'
import './suggestedSearches.scss'

const SuggestedSearches = ({ suggestedSearches, query, setQuery, seachButtonRef }) => {
  const { label, suggestions } = suggestedSearches
  const [pressedId, setPressedId] = useState(null);

  const handleOnClick = (event, id) => {
    const buttonValue = event.currentTarget.value
    setQuery(buttonValue)
    setTimeout(() => seachButtonRef.current.click())
    setPressedId(id)
  }

  return (
    <>
      {(suggestions && suggestions.length > 0) &&
        <div className='suggested-searches'>
          <h3 className='label'>{label}</h3>
          <div className='suggested-buttons'>
            {suggestions.map((suggestion) => (
              <button
                key={suggestion.id}
                value={suggestion.text}
                className={`suggested-button ${suggestion.text === query ? 'selected' : ''}`}
                onClick={(e) => handleOnClick(e, suggestion.id)}
                aria-pressed={pressedId === suggestion.id}
              >
                {suggestion.text}
              </button>
            ))}
          </div>
        </div>}
    </>
  )
}

export default SuggestedSearches
关键优化点
  • 确保判断aria-pressed的标识唯一且存在,避免因undefined导致全选
  • 简化状态逻辑:用单个值记录当前选中的按钮标识,其他按钮会因不匹配自动变为false,无需手动清空所有状态
  • 优化key取值:对象数组用唯一id作为key;字符串数组确保内容唯一,避免重复key引发渲染问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:13:29