
本文介绍了onClick() 仅适用于第一次点击 - React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让 onClick() 函数适用于每个按钮(结果相同),但截至目前 onClick() 仅适用一次.
如果我再次单击按钮(相同或不同),弹出窗口将不再起作用.
你能帮忙吗?我不知道如何修复它.
function Challange() {const [isPopped, setPop] = useState(false);const pop = () =>{设置流行(真);};返回 (<>{isPopped &&<Dialog2/>}<div className="挑战"><h1 className="newchallenge">选择新挑战</h1><button className="challangeBtn";onClick={pop}>吃素食(31天)<button className="challangeBtn";onClick={pop}>骑自行车上班(14天)<button className="challangeBtn";onClick={pop}>回收塑料瓶(31 天)<button className="challangeBtn";onClick={pop}>使用公共交通工具上下班(31天)<button className="challangeBtn";onClick={pop}>不要坐飞机(365天)
</>);}导出默认挑战;
解决方案
在您的情况下 setPop
可以采用返回布尔值的布尔值或方法.在 React 中处理切换的最佳实践如下所示:
const pop = () =>{setPop(currentValue => !currentValue);};
此外,使用 useCallback
钩子来管理单击等事件并避免在每次渲染时重新初始化您的方法:
const pop = useCallback(() => {setPop(currentValue => !currentValue);}, []);
I am trying to make onClick() function work for every button (its the same result), but as of now onClick() works only once.
If I click on a button again (the same or different) the pop up doesn't work anymore.
Could you please help? I cannot figure out how to fix it.
function Challange() {
const [isPopped, setPop] = useState(false);
const pop = () => {
setPop(true);
};
return (
<>
{isPopped && <Dialog2 />}
<div className="challanges">
<h1 className="newchallenge">Choose New Challange</h1>
<button className="challangeBtn" onClick={pop}>
Eat Vegetarian (31days)
</button>
<button className="challangeBtn" onClick={pop}>
Take the bike to work (14days)
</button>
<button className="challangeBtn" onClick={pop}>
Recycle your plastic bottles (31days)
</button>
<button className="challangeBtn" onClick={pop}>
Use public transport to commute (31days)
</button>
<button className="challangeBtn" onClick={pop}>
Don't fly an airplane (365days)
</button>
</div>
</>
);
}
export default Challange;
解决方案
in your case setPop
can take boolean value OR method that returns boolean.Best practices for handle toggling in React looks like:
const pop = () => {
setPop(currentValue => !currentValue);
};
Also, use useCallback
hook to manage events like click and avoid re-initialization of your method on each render:
const pop = useCallback(() => {
setPop(currentValue => !currentValue);
}, []);
这篇关于onClick() 仅适用于第一次点击 - React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!