英文:
document.querySelector('something').addEventListener(), how do I achieve the functionality of this snippet on reactJS
问题
我试图实现Diprella登录设计,以创建我的个人登录页面,查看多个来源,我找到了一个用于页面的CSS和Html设计,但是,我尝试在reactJs上实现它,我遇到了一个问题,每次重新加载页面时,所有组件都消失。在多次尝试和错误的迭代后,我将问题缩小到以下代码片段:
document.querySelector('.img-btn').addEventListener('click', function() {
document.querySelector('.cont').classList.toggle('s-signup');
});
是否有解决此问题的方法,根据我收集的信息,可以使用useRef来代替querySelector。但由于我对React和前端开发都不熟悉,所以很难解决这个问题。任何帮助将不胜感激!
我尝试使用onClick并创建一个返回的函数:
document.querySelector('.cont').classList.toggle('s-signup');
问题仍然存在,重新加载时所有现有组件都会消失。
英文:
I was trying to achieve Diprella Login design to create my own personal login page, looking through multiple sources, I found a CSS and Html design for the page
however, I'm trying to implement it on reactJs. and I'm facing an Issue where every time I reload the page all components disappear. after multiple iterations of trial and error, I narrowed the issue down to this following snippet of the code
document.querySelector('.img-btn').addEventListener('click', function()
{
document.querySelector('.cont').classList.toggle('s-signup')
}
);
is there any way to solve this issue, from what I've gathered, useRef can be used instead of querySelector. but since I'm new to react as well front end Development, I'm finding it hard to solve the issue. Any Help would be greatly appreciated!
I tried using onClick and created a function which returns
document.querySelector('.cont').classList.toggle('s-signup')
the issue still pertains where reload disappears all the existing components
答案1
得分: 0
切换类的点击操作可以通过在状态中存储布尔值来实现。在下面的示例中,我使用了[state hook][1]。
**[Codesandbox 演示][2]**
import { useState } from 'react';
function App() {
const [signUp, setSignUp] = useState(false)
return (
<div className={`cont${(signUp ? " s-signup" : "")}`}>
<img className="img-btn" src="..." onClick={() => setSignUp(!signUp)} />
</div>
);
}
[1]: https://reactjs.org/docs/hooks-state.html
[2]: https://codesandbox.io/s/divine-thunder-vu3tmg
英文:
Toggling a class on click can be done by storing a boolean in state. In the below example I use a state hook.
import { useState } from 'react';
function App() {
const [signUp, setSignUp] = useState(false)
return (
<div className={`cont${(signUp ? " s-signup" : "")}`}>
<img className="img-btn" src="..." onClick={() => setSignUp(!signUp)} />
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论