when i add the event listener to my react app everything disappears idk what's the problem

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

when i add the event listener to my react app everything disappears idk what's the problem

问题

我想要为我的导航栏按钮添加一个点击事件,但是当我添加了事件监听器后,一切都消失了。这是我的代码:

import React from "react";
import { Bars3Icon } from '@heroicons/react/24/solid';

const Navbar = () => {
    let btn = document.querySelector('icon');
    let menu = document.querySelector('menu1');
    
    btn.addEventListener('click', () => {
        menu.classList.toggle('hidden');
    })
    
    return (
        <div className="bg-[#1f1e20]">
            <div>
                <button id="icon"><Bars3Icon className="text-white w-8 h-8 relative left-[320px] top-2" /></button>
                <ul id="menu1" className="grid text-white text-center gap-4 p-4">
                    <a href=""><li>Home</li></a>
                    <a href=""><li>About</li></a>
                    <a href=""><li>Contact</li></a>
                </ul>
            </div>
        </div>
    )
}

export default Navbar;

我不知道我漏掉了什么,我也查看了一些源代码。

英文:

i want to add a onclick event to my navbar button but when i add the eventistener everything disappears. here's my code:

import React from &quot;react&quot;;
import {Bars3Icon} from &#39;@heroicons/react/24/solid&#39;


const Navbar = () =&gt; {
    let btn = document.querySelector(&#39;icon&#39;);
    let menu = document.querySelector(&#39;menu1&#39;);
    
    btn.addEventListener(&#39;click&#39; , () =&gt; {
        menu.classList.toggle(&#39;hidden&#39;);
    })
    return (
    &lt;div className=&quot;bg-[#1f1e20]&quot;&gt;
        &lt;div&gt;
           &lt;button id=&quot;icon&quot;&gt;&lt;Bars3Icon className=&quot;text-white w-8 h-8 relative left-[320px] top-2&quot; /&gt;&lt;/button&gt;
            &lt;ul id=&quot;menu1&quot; className=&quot;grid text-white text-center gap-4 p-4  &quot;&gt;
                &lt;a href=&quot;&quot;&gt;&lt;il&gt;
                Home
                &lt;/il&gt;&lt;/a&gt;
                &lt;a href=&quot;&quot;&gt;&lt;il&gt;
                About
            &lt;/il&gt;&lt;/a&gt;
            &lt;a href=&quot;&quot;&gt; &lt;il&gt;
                Contact
            &lt;/il&gt;&lt;/a&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    )
}



export default Navbar;

idk what am i missing i reviewed some source codes aswell.

答案1

得分: 0

你的做法有些不对。你没有按照 React 的正确方式来使用,而是依赖于通过查询选择器附加和删除属性。试着以 "React" 的方式来思考。

如果你想要切换一个类,创建一个状态变量来保存在重新渲染之间的值。

const [hidden, setHidden] = useState(false);

然后,你应该修改你的按钮组件以使用 onClick 属性。

<button onClick={() => setHidden(!hidden)}>
    <Bars3Icon ... />
</button>

最后,使用三元运算符来切换你的类:

<Bars3Icon className={`text-white w-8 h-8 relative left-[320px] top-2 ${hidden ? 'hidden' : ''}`} />
英文:

You're kind of going about this all wrong. You are not using React the way it is meant to be used, relying on attaching and removing properties via query selection. Try thinking about it the "React" way.

If you want to toggle on a class, create a state variable that saves the value between re-renders.

const [hidden, setHidden] = useState(false);

Then you should change your button component to use the onClick props.

&lt;button onClick={() =&gt; setHidden(!hidden) }&gt;
    &lt;Bars3Icon ... /&gt; 
&lt;/button&gt;

Finally, toggle your class using a ternary operator;

&lt;Bars3Icon className={`text-white w-8 h-8 relative left-[320px] top-2 ${hidden ? &#39;hidden&#39; : &#39;&#39;}`} /&gt;

答案2

得分: -1

看起来您可能在querySelector中缺少了class/id

确保在querySelector中添加正确的iconmenu类/方法。

此外,请尽量不要直接操作React中的DOM元素。您可以使用React的状态和事件处理来实现所需的行为。

import React, { useState } from "react";
import { Bars3Icon } from '@heroicons/react/24/solid';

const Navbar = () => {
  const [menuVisible, setMenuVisible] = useState(false);

  const toggleMenu = () => {
    setMenuVisible(!menuVisible);
  };

  return (
    <div className="bg-[#1f1e20]">
      <div>
        <button id="icon" onClick={toggleMenu}>
          <Bars3Icon className="text-white w-8 h-8 relative left-[320px] top-2" />
        </button>
        <ul id="menu1" className={`grid text-white text-center gap-4 p-4 ${menuVisible ? '' : 'hidden'}`}>
          <li>
            <a href="">Home</a>
          </li>
          <li>
            <a href="">About</a>
          </li>
          <li>
            <a href="">Contact</a>
          </li>
        </ul>
      </div>
    </div>
  );
};

export default Navbar;

这应该会产生所期望的结果。

英文:

Looks like you're probably missing the class/id in the querySelector.

Make sure you add the correct class/method for icon and menu in the querySelector.

Also, try not to manipulate DOM elements directly in react.
You could use React's state and event handling to achieve the desired behavior.

import React, { useState } from &quot;react&quot;;
import { Bars3Icon } from &#39;@heroicons/react/24/solid&#39;;

const Navbar = () =&gt; {
  const [menuVisible, setMenuVisible] = useState(false);

  const toggleMenu = () =&gt; {
    setMenuVisible(!menuVisible);
  };

  return (
    &lt;div className=&quot;bg-[#1f1e20]&quot;&gt;
      &lt;div&gt;
        &lt;button id=&quot;icon&quot; onClick={toggleMenu}&gt;
          &lt;Bars3Icon className=&quot;text-white w-8 h-8 relative left-[320px] top-2&quot; /&gt;
        &lt;/button&gt;
        &lt;ul id=&quot;menu1&quot; className={`grid text-white text-center gap-4 p-4 ${menuVisible ? &#39;&#39; : &#39;hidden&#39;}`}&gt;
          &lt;li&gt;
            &lt;a href=&quot;&quot;&gt;Home&lt;/a&gt;
          &lt;/li&gt;
          &lt;li&gt;
            &lt;a href=&quot;&quot;&gt;About&lt;/a&gt;
          &lt;/li&gt;
          &lt;li&gt;
            &lt;a href=&quot;&quot;&gt;Contact&lt;/a&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

export default Navbar;

This should give the desired result

huangapple
  • 本文由 发表于 2023年6月1日 16:37:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380064.html
匿名

发表评论

匿名网友

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

确定