在ReactJS中,单击时显示一个div并隐藏另一个div。

huangapple go评论69阅读模式
英文:

Show one div hide another onclick in ReactJS

问题

import { useState } from "react";

export default function LoginBox() {
  const [show, setShow] = useState('');
  const [sidebarActive, setSidebarActive] = useState(false);

  const handleClick = (id) => {
    if (show === id) {
      setShow('');
      setSidebarActive(false);
    } else {
      setShow(id);
      setSidebarActive(true);
    }
  };

  const handleParentClick = () => {
    if (sidebarActive) {
      setShow('');
      setSidebarActive(false);
    }
  };

  return (
    <>
      <div id="sidebarLeft" className={`hideBar ${sidebarActive ? 'active' : ''}`}>
        <div className="leftBarDetails">
          <div className="home topButton" onClick={() => handleClick('login')}>
            <div className="sideButtonIcon">
              <i className="fa-solid fa-user"></i>
            </div>
          </div>
          <div className="home topButton" onClick={() => handleClick('controls')}>
            <div className="sideButtonIcon">
              <i className="fa-solid fa-gamepad"></i>
            </div>
          </div>
        </div>
      </div>

      {show === 'login' && (
        <div className="logincontainer hidden" onClick={handleParentClick}>
          <label className="close-btn fas fa-times" onClick={() => setShow('')}></label>
          <div className="text">Login Form</div>
          <form action="#">
            <div className="data">
              <label>Email</label>
              <input type="text" required />
            </div>
            <div className="data">
              <label>Password</label>
              <input type="password" required />
            </div>
            <div className="forgot-pass">
              <a href="#">Forgot Password?</a>
            </div>
            <div className="btn">
              <div className="inner"></div>
              <button type="submit">login</button>
            </div>
            <div className="signup-link">
              Need an account? <a href="#"> Signup now</a>
            </div>
          </form>
        </div>
      )}

      {show === 'controls' && (
        <div className="logincontainer hidden" onClick={handleParentClick}>
          <label className="close-btn fas fa-times" onClick={() => setShow('')}></label>
          <div className="text">
            <p>
              <b>CONTROLS</b>:<br />
              <b>WASD || ARROW KEYS</b> - Move<br />
              <b>R|F || SPACEBAR | SHIFT</b> - Up | Down<br />
              <b>LEFT CLICK AND MOUSE</b> - Camera Movement<br />
              <b>ESC</b> - Exit Camera Movement<br />
            </p>
          </div>
        </div>
      )}
    </>
  );
}
英文:

Quite new to ReactJS and using it for web development. How do I show one div but hide all others onclick, all divs are hidden on purpose (popup divs from onclick on sidebar menu).

I have two buttons on a side panel and two divs that are hidden on page load. Currently I have each of them hiding/showing onclick but the problem is if one is opened when the other is opened then they both appear which is not what I want (as they cover each other)

Current code:


export default function LoginBox() { 
  const [show, setShow] =  useState(false);
  const [showControls, setShowControls] =  useState(false);

  return (
    &lt;&gt;

&lt;div id=&quot;sidebarLeft&quot; className=&quot;hideBar&quot;&gt;
        &lt;div className=&quot;leftBarDetails&quot;&gt;
          
          &lt;div className=&quot;home topButton&quot;&gt;
            &lt;div className=&quot;sideButtonIcon&quot; 
            
            onClick={()=&gt;{setShow(!show)}}
            
            &gt;
              &lt;i className=&quot;fa-solid fa-user&quot;&gt;&lt;/i&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div className=&quot;home topButton&quot;&gt;
            &lt;div className=&quot;sideButtonIcon&quot; onClick={()=&gt;{setShowControls(!showControls)}}&gt;
              &lt;i className=&quot;fa-solid fa-gamepad&quot;&gt;&lt;/i&gt;
            &lt;/div&gt;
          &lt;/div&gt;
    
        &lt;/div&gt;
      &lt;/div&gt;
     {show &amp;&amp; &lt;div className=&quot;logincontainer hidden&quot;&gt;
            &lt;label className=&quot;close-btn fas fa-times&quot; onClick={()=&gt;{setShow(!show)}}&gt;&lt;/label&gt;
            &lt;div className=&quot;text&quot;&gt;Login Form&lt;/div&gt;
            &lt;form action=&quot;#&quot;&gt;
              &lt;div className=&quot;data&quot;&gt;
                &lt;label&gt;Email&lt;/label&gt;
                &lt;input type=&quot;text&quot; required /&gt;
              &lt;/div&gt;
              &lt;div className=&quot;data&quot;&gt;
                &lt;label&gt;Password&lt;/label&gt;
                &lt;input type=&quot;password&quot; required /&gt;
              &lt;/div&gt;
              &lt;div className=&quot;forgot-pass&quot;&gt;
                &lt;a href=&quot;#&quot;&gt;Forgot Password?&lt;/a&gt;
              &lt;/div&gt;
              &lt;div className=&quot;btn&quot;&gt;
                &lt;div className=&quot;inner&quot;&gt;&lt;/div&gt;
                &lt;button type=&quot;submit&quot;&gt;login&lt;/button&gt;
              &lt;/div&gt;
              &lt;div className=&quot;signup-link&quot;&gt;
                Need an account?
                &lt;a href=&quot;#&quot;&gt; Signup now&lt;/a&gt;
              &lt;/div&gt;
            &lt;/form&gt;
          &lt;/div&gt;}
     {showControls &amp;&amp; &lt;div className=&quot;logincontainer hidden&quot;&gt;
            &lt;label className=&quot;close-btn fas fa-times&quot; 
            onClick={()=&gt;{setShowControls(!showControls)}}&gt;

            &lt;/label&gt;
            &lt;div className=&quot;text&quot;&gt; &lt;p&gt;
              &lt;b&gt;CONTROLS&lt;/b&gt;
              :&lt;br /&gt;
              &lt;b&gt;WASD || ARROW KEYS&lt;/b&gt;
              - Move&lt;br /&gt;
              &lt;b&gt;R|F || SPACEBAR | SHIFT&lt;/b&gt;
              - Up | Down&lt;br /&gt;
            &lt;/p&gt;&lt;/div&gt;
            
          &lt;/div&gt;}

After some research and assistance from chatgpt I solved my issue with the following code:


import { useState } from &quot;react&quot;;

export default function LoginBox() {
  const [show, setShow] = useState(&#39;&#39;);
  const [sidebarActive, setSidebarActive] = useState(false);

  const handleClick = (id) =&gt; {
    if (show === id) {
      setShow(&#39;&#39;);
      setSidebarActive(false);
    } else {
      setShow(id);
      setSidebarActive(true);
    }
  };

  const handleParentClick = () =&gt; {
    if (sidebarActive) {
      setShow(&#39;&#39;);
      setSidebarActive(false);
    }
  };

  return (
    &lt;&gt;
      &lt;div id=&quot;sidebarLeft&quot; className={`hideBar ${sidebarActive ? &#39;active&#39; : &#39;&#39;}`}&gt;
        &lt;div className=&quot;leftBarDetails&quot;&gt;
        
          &lt;div className=&quot;home topButton&quot; onClick={() =&gt; handleClick(&#39;login&#39;)}&gt;
            &lt;div className=&quot;sideButtonIcon&quot;&gt;
              &lt;i className=&quot;fa-solid fa-user&quot;&gt;&lt;/i&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div className=&quot;home topButton&quot; onClick={() =&gt; handleClick(&#39;controls&#39;)}&gt;
            &lt;div className=&quot;sideButtonIcon&quot;&gt;
              &lt;i className=&quot;fa-solid fa-gamepad&quot;&gt;&lt;/i&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;

      {show === &#39;login&#39; &amp;&amp; (
        &lt;div className=&quot;logincontainer hidden&quot; onClick={handleParentClick}&gt;
          &lt;label className=&quot;close-btn fas fa-times&quot; onClick={() =&gt; setShow(&#39;&#39;)}&gt;&lt;/label&gt;
          &lt;div className=&quot;text&quot;&gt;Login Form&lt;/div&gt;
          &lt;form action=&quot;#&quot;&gt;
            &lt;div className=&quot;data&quot;&gt;
              &lt;label&gt;Email&lt;/label&gt;
              &lt;input type=&quot;text&quot; required /&gt;
            &lt;/div&gt;
            &lt;div className=&quot;data&quot;&gt;
              &lt;label&gt;Password&lt;/label&gt;
              &lt;input type=&quot;password&quot; required /&gt;
            &lt;/div&gt;
            &lt;div className=&quot;forgot-pass&quot;&gt;
              &lt;a href=&quot;#&quot;&gt;Forgot Password?&lt;/a&gt;
            &lt;/div&gt;
            &lt;div className=&quot;btn&quot;&gt;
              &lt;div className=&quot;inner&quot;&gt;&lt;/div&gt;
              &lt;button type=&quot;submit&quot;&gt;login&lt;/button&gt;
            &lt;/div&gt;
            &lt;div className=&quot;signup-link&quot;&gt;
              Need an account? &lt;a href=&quot;#&quot;&gt; Signup now&lt;/a&gt;
            &lt;/div&gt;
          &lt;/form&gt;
        &lt;/div&gt;
      )}

      {show === &#39;controls&#39; &amp;&amp; (
        &lt;div className=&quot;logincontainer hidden&quot; onClick={handleParentClick}&gt;
          &lt;label className=&quot;close-btn fas fa-times&quot; onClick={() =&gt; setShow(&#39;&#39;)}&gt;&lt;/label&gt;
          &lt;div className=&quot;text&quot;&gt;
            &lt;p&gt;
              &lt;b&gt;CONTROLS&lt;/b&gt;:&lt;br /&gt;
              &lt;b&gt;WASD || ARROW KEYS&lt;/b&gt; - Move&lt;br /&gt;
              &lt;b&gt;R|F || SPACEBAR | SHIFT&lt;/b&gt; - Up | Down&lt;br /&gt;
              &lt;b&gt;LEFT CLICK AND MOUSE&lt;/b&gt; - Camera Movement&lt;br /&gt;
              &lt;b&gt;ESC&lt;/b&gt; - Exit Camera Movement&lt;br /&gt;
            &lt;/p&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      )}  
    &lt;/&gt;
  );
}

Thanks everyone for the help anyway and I hope it helps someone else

答案1

得分: 1

有几种方法可以解决这个问题,例如,您可以添加两个 useEffect 钩子,它们将检查其他 div 是否显示,并相应地隐藏它们:

useEffect(() => {
  if (show) {
    setShowControls(false);
  }
}, [show]);

useEffect(() => {
  if (showControls) {
    setShow(false);
  }
}, [showControls]);

不要忘记添加导入语句:

import { useEffect } from 'react';

另一种选项 是直接在 onClick 函数中添加这个逻辑:

<div className="home topButton">
  <div
    className="sideButtonIcon"
    onClick={() => { 
      // 这个检查确保如果之前显示了其他的 div,它们会隐藏
      if (showControls) {
        setShowControls(false);
      }
      setShow(!show);
    }}
  >
    <i className="fa-solid fa-user"></i>
  </div>
</div>

以及:

<div className="home topButton">
  <div
    className="sideButtonIcon"
    onClick={() => {
      // 这个检查确保如果之前显示了其他的 div,它们会隐藏
      if (show) {
        setShow(false);
      }
      setShowControls(!showControls);
    }}
  >
    <i className="fa-solid fa-gamepad"></i>
  </div>
</div>
英文:

There are several ways to solve this, for example you can add two useEffect hooks that will check whether the other divs are shown and hide them accordingly:

useEffect(() =&gt; {
if (show) {
setShowControls(false);
}
}, [show]);
useEffect(() =&gt; {
if (showControls) {
setShow(false);
}
}, [showControls]);

And don't forget to add the import:

import { useEffect } from &#39;react&#39;;

Another option is to add this logic in the onClick functions directly:

&lt;div className=&quot;home topButton&quot;&gt;
&lt;div
className=&quot;sideButtonIcon&quot;
onClick={() =&gt; { 
// This check ensures the other div will hide if previously shown
if (showControls) {
setShowControls(false);
}
setShow(!show);
}}
&gt;
&lt;i className=&quot;fa-solid fa-user&quot;&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;/div&gt;

And:

&lt;div className=&quot;home topButton&quot;&gt;
&lt;div
className=&quot;sideButtonIcon&quot;
onClick={() =&gt; {
// This check ensures the other div will hide if previously shown
if (show) {
setShow(false);
}
setShowControls(!showControls);
}}
&gt;
&lt;i className=&quot;fa-solid fa-gamepad&quot;&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;/div&gt;

答案2

得分: 0

我已成功解决了这个问题,我已经在我的问题中更新了解决方案。

我们引入了一个名为handleClick的函数,它接受一个表示要显示的div的id参数。当单击按钮(位于div侧边栏内的div)时,将调用此函数,并将show状态更新为该id。

根据show状态,将显示与其id匹配的适当div值。当单击关闭按钮时,我们将show状态设置回一个空字符串('')以隐藏所有div。

作为额外的功能,使用了另一个useState hook来在按钮(位于侧边栏内与要显示/隐藏的特定框对应的div)切换时显示和隐藏框。

英文:

I have managed to solve the issue myself, I have update my question with the solution I came to.

I we introduced a handleClick function that takes an id parameter representing the id of the div to be shown. When a button (div inside sidebar of divs) is clicked, this function is called with the corresponding id, and it updates the show state to that id.

The appropriate div based on the show state will be shown if its id matches the show state value. When the close button is clicked, we set the show state back to an empty string ('') to hide all divs.

As an additional functionality another useState hook was used to show and hide the box when the button (div inside the sidebar corresponding to a certain box to show/hide) is toggled.

huangapple
  • 本文由 发表于 2023年7月3日 15:54:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定