【问题标题】:how i can enable only one button onclick and disable all other using react js我如何使用 react js 仅启用一个按钮 onclick 并禁用所有其他按钮
【发布时间】:2022-09-27 22:58:54
【问题描述】:

我有一个从按钮中选择值的应用程序让我告诉你 enter image description here

每当我们想单击一个按钮时,禁用除我选择的所有其他按钮,我不明白如何实现它。

这是代码简化: https://github.com/mehditaib03/Tip-/blob/main/src/Components/Billinput.jsx

对于块代码和概念,请考虑: https://scrimba.com/scrim/c4LEQwf9

<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>
export function OtherMethod () {
 
  
    const [current,setCurrent]= useState(true)
  
    function myFunc(e){
        //loop overr each node of button
        //setcurrent node to false 
        //setOther node to true   
        console.log(e.target.disabled)
           
      }
      
   
  return (
      <div id=\"container\" >
          <button id=\"1\" disabled={current} onClick={myFunc}> click me</button>
          <button id=\"2\" disabled={current} onClick={myFunc}>abc</button>
          <button id=\"3\" disabled={current} onClick={myFunc} >def</button>
          <button id=\"4\" disabled={current} onClick={myFunc}>ghi</button>
      </div>   
  )
}

    标签: reactjs react-hooks


    【解决方案1】:

    不要将current 设为布尔值,而是将其设为string | null。然后,将current 设置为handleClick 函数中按钮元素的id。我创建了一个新的Button 组件来封装逻辑。但这里的关键是disabled={current &amp;&amp; current !== id},它会禁用除最后一次单击的按钮之外的所有按钮。

    const Button = ({ children, current, id, onClick }) => {
      return (
        <button id={id} disabled={current && current !== id} onClick={onClick}>
          {children}
        </button>
      );
    }
    
    export function OtherMethod () { 
        const [current,setCurrent]= useState<string | null>(null);
      
        const handleClick = e => {
           setCurrent(e.target.id);
        }
        
      return (
          <div id="container" >
              <Button id="1" current={current} onClick={handleClick}> click me</button>
              <Button id="2" current={current} onClick={handleClick}>abc</button>
              <Button id="3" current={current} onClick={handleClick} >def</button>
              <Button id="4" current={current} onClick={handleClick}>ghi</button>
          </div>   
      )
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      相关资源
      最近更新 更多