What is the equivalent of add.classList in React for toggling visibility?

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

What is the equivalent of add.classList in React for toggling visibility?

问题

在React中添加和移除元素的类

我对React完全不熟悉,但基本上我一直在尝试当你点击一个按钮时,使一个容器从隐藏变为可见。
通常情况下,我会使用事件监听器并使用add.classListremove.classList,但我无法在React中找到相应的等价物?
我尝试使用useState和其他一切来解决它,但我觉得我可能只是忽视了一些简单的东西。
我真的会非常感谢一些帮助,已经过去好几个小时了,我的小脑袋要爆炸了。

英文:

Adding and removing classes to elements in React

I’m a complete newb with React but basically I’ve been trying to make it so that a container goes from hidden to visible when you click a button.
Usually I’d just do an eventListner and add.classList or remove.classList but I can’t find the equivalent to that in react ?
I’ve tried figuring it out with useState and everything but I feel like I’m just overlooking something simple.
I would really appreciate some help it’s been like hours and my tiny brain is gonna explode

答案1

得分: 1

我建议添加一个条件来渲染元素/组件,而不是使用类。

const [visible, setVisible] = useState(false);

return (
  <div>
    <button onClick={() => setVisible(!visible)}>toggle</button>
    {visible && <span>hello</span>}
  </div>
);
英文:

I would recommend adding a condition to render the element/component instead of using classes.

const [visible, setVisible] = useState(false);

return (
  &lt;div&gt;
    &lt;button onClick={() =&gt; setVisible(!visible)}&gt;toggle&lt;/button&gt;
    {visible &amp;&amp; &lt;span&gt;hello&lt;/span&gt;}
  &lt;/div&gt;
);

huangapple
  • 本文由 发表于 2023年6月2日 12:32:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387124.html
匿名

发表评论

匿名网友

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

确定