单击时 - 清除按钮状态,然后将当前按钮的状态设置为 true - React

问题描述 投票:0回答:1

我是反应新手,我正在尝试向我的按钮添加咏叹调标签,以显示其状态以提高可访问性。我目前可以在单击按钮时更改状态,但它意外地更改了所有按钮的状态。我知道我需要在按钮上附加一个 id,但我可以使用一些帮助来告诉我哪里出错了。

这是我目前拥有的代码:

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

const SuggestedSearches = ({ suggestedSearches, query, setQuery, seachButtonRef }) => {
  const { label, suggestions } = suggestedSearches
  const [ariaPressed, setAriaPressed] = useState(false);
  const toggleAria = (id) => {
    setAriaPressed(ariaPressed => ({
        ...ariaPressed,
        [id]: !ariaPressed[id]
    }))
  }

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

  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}
                aria-pressed={ariaPressed[suggestion.id]}
              >
                {suggestion}
              </button>
            ))}
          </div>
        </div>}
    </>
  )
}

export default SuggestedSearches

预期的功能是,当单击按钮时,所有按钮的“aria-pressed”状态都会被清除,然后当前按钮的“aria-pressed”状态将设置为 true。

任何帮助将不胜感激!

javascript reactjs frontend
1个回答
0
投票

预期的功能是,当单击按钮时,所有按钮的“aria-pressed”状态都会被清除,然后当前按钮的“aria-pressed”状态将设置为 true。

在此用例中,您无需维护所有按钮的 aria-pressed 值的状态。

您可以有一个状态来跟踪其 aria-pressed 应该为 true 的按钮的 id。您可以使用状态

ariaPressedId
,也许将默认值设置为
-1

现在设置按钮

aria-pressed
的值时,可以设置逻辑为:

aria-pressed={ariaPressedId === suggestion.id}

这样只有该按钮的

aria-pressed
值为
true
,其余为
false

这就是

toggleAria
函数的样子 :

const toggleAria = (id) => {
    setAriaPressedId(id)
  }

handleChange
中,您必须将
id
传递给
toggleAria
所以在按钮的 onClick 中将如下所示:

onClick={() => handleChange(suggestion.id)}

我希望这个答案是你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.