javascript React useState动态切换多个按钮

6tqwzwtp  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(126)

我试图切换常见问题按钮,基本上当button 1被点击-> state 1被打开为真(工具提示打开)-> button 2被点击-> state 2为真,state 1被打开为假,工具提示关闭。这是我目前拥有的

const App = () => {

const [isOpen, setIsOpen] = useState(false);
const faqTipBtns = ['faqBtn1', 'faqBtn2', 'faqBtn3'];

const FaqtipIcon = (id) => {
     return(
         <button id = {id}
          onClick = {() => toggleFaqTipBtn()}>
          <FaqtipIcon isOpen = {isOpen}/>
         </button>
     )
};

const toggleFaqTipBtn = () => {

  {faqTipBtns.map((id) => {
        setIsOpen((prev) => !prev)
})}

   return (
     <form>
        <RadioGroup>
         <div>
            <Radio
               id='idA'
               label = 'SomeLabel'/>
               {FaqtipIcon('idA')}
           </div>
           {isOpen && (
                <div>
                   <FaqtipContent
                     isOpen = {isOpen}
                     content = {<p>Some Content</p>} 
                    />
                </div>   
        </RadioGroup>
     </form>
)

}
64jmpszr

64jmpszr1#

这是你要找的按钮吗?

const FAQ_TIP_BUTTONS = ["faqBtn1", "faqBtn2", "faqBtn3"];

const App = () => {
  // Store active button id
  const [isOpen, setIsOpen] = useState("faqBtn1");

  return (
    <form>
      <RadioGroup>
        <div>
          <Radio id="idA" label="SomeLabel" />
          {/* Display all buttons */}
          {FAQ_TIP_BUTTONS.map((id) => (
            <FaqtipIcon isOpen={id === isOpen} onClick={() => setIsOpen(id)} />
          ))}
        </div>
        {isOpen && (
          <div>
            <FaqtipContent isOpen={isOpen} content={<p>Some Content</p>} />
          </div>
        )}
      </RadioGroup>
    </form>
  );
};

const FaqtipIcon = ({ isOpen, onClick }) => {
  return (
    <button onClick={onClick}>
      <FaqtipIcon isOpen={isOpen} />
    </button>
  );
};
ghhkc1vu

ghhkc1vu2#

React useState动态切换多个按钮

我理解你的问题,就像显示按钮相关的工具提示一样。example

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [selectedBtn, setSelectedBtn] = useState("");
  const faqTipBtns = ["faqBtn1", "faqBtn2", "faqBtn3"];

  return (
    <div className="App">
      <h1>show Tooltip that related with his button</h1>
      {faqTipBtns.map((button) => (
        <div>
          {selectedBtn === button ? <div> Tooltip {button}</div> : <div />}
          <button onClick={() => setSelectedBtn(button)}>{button}</button>
        </div>
      ))}
    </div>
  );
}

相关问题