onClick() works on the first click only - React

跟風遠走 提交于 2021-01-29 10:32:34

问题


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;

回答1:


Your pop function code only sets the state to true, so it will never be false again. You may change it like this.

const pop = () => {
        setPop(!isPopped);
      };



回答2:


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);
}, []);


来源:https://stackoverflow.com/questions/64936603/onclick-works-on-the-first-click-only-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!