英文:
What is the equivalent of add.classList in React for toggling visibility?
问题
在React中添加和移除元素的类
我对React完全不熟悉,但基本上我一直在尝试当你点击一个按钮时,使一个容器从隐藏变为可见。
通常情况下,我会使用事件监听器并使用add.classList
或remove.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 (
<div>
<button onClick={() => setVisible(!visible)}>toggle</button>
{visible && <span>hello</span>}
</div>
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论