【问题标题】:Is there a way to iterate over a list of buttons & toggle a specific button when it is clicked?有没有办法遍历按钮列表并在单击特定按钮时切换它?
【发布时间】:2021-06-08 21:10:47
【问题描述】:

问题 - 当我单击一个按钮显示答案文本时,另一个按钮也会打开。我只想在我点击每个问题时打开它的答案。

我的代码 -

import React, { useState } from "react"

const Questions = [
  {
    question: "What is your favourite colour?",
    answer: "My favourite colour is pink",
  },
  {
    question: "What is your favourite animal?",
    answer: "My favourite animal is a monkey",
  },
]

const FAQs = () => {
  const [isOpen, setIsOpen] = useState(false)
  const toggle = () => setIsOpen(!isOpen)

  return (
    <div>
      {Questions.map((element, i, array) => {
        return (
          <div>
            <button onClick={toggle} key={i}>
              {element.question}
            </button>
            {isOpen && <p key={i}>{element.answer}</p>}
          </div>
        )
      })}
    </div>
  )
}

export default FAQs

【问题讨论】:

  • 发生这种情况是因为您正在映射您的问题,并为每个问题创建一个按钮。您传递的 onClick 函数对于每个函数都是相同的。本质上,这两个按钮的行为都符合您的代码预期,当单击任一按钮时,isOpen 的值为 true。

标签: javascript reactjs iterator react-hooks


【解决方案1】:

isOpen 设为对象,然后根据需要将布尔值分配为isOpen[index]=false|true。在 HTML 中,绑定为isOpen[i] &amp;&amp;...

您在这里所做的问题是变量 isOpen 与您的 Questions 对象无关。

【讨论】:

    【解决方案2】:

    你可以把isOpen改成一个对象,这样设置。

    const [isOpen, setIsOpen] = useState({})
    const toggle = (i) => setIsOpen({...isOpen, [i]:!isOpen[i]})
    

    那就这样用吧

    <button onClick={() => toggle(i)} key={i}>
        {element.question}
    </button>
    {isOpen[i] && <p key={i}>{element.answer}</p>}
    

    【讨论】:

    • i:!isOpen[i] 应该是[i]:!isOpen[i]
    • @Adarsh Mohan 已修复。
    • 非常感谢!
    • @Kimberley 请考虑将答案标记为例外,如果它对您将来有相同问题的人有用。
    猜你喜欢
    • 1970-01-01
    • 2018-12-02
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多