简体   繁体   中英

onClick doesn't work on first click after rerender

const NavigationButtons = ({onBtnClicked, btnClass, label, route, btnAct}) => {
  return (
    <p
      className={`btn ${btnClass} ${btnAct}`}
      onClick={() => onBtnClicked(route)}>
      {label}
    </p>
  );
};

This is my button component, I'm giving it to another component as btns1 props

 {!isSigned?btns1:windowPixel?btns1:null}

Basically, when isSigned is false, btns1 is rendered. There's really no problem here. When isSigned is true, it checks if windowPixel is true, this is changed to true by App.js as a state by measuring the current window. It works perfectly unless I click the button. Resize the window where windowPixel will be false, then on my first click, it doesn't trigger onClick. After that onClick works again.

componentDidMount() {
  if (window.matchMedia(`(max-width: 990px)`).matches) {
    this.resizeWindow(true);
  }
  window.addEventListener("resize", () => this.resizeWindow(window.matchMedia(`(max-width: 990px)`).matches));
}

This is what checks the window size for windowPixel. chatScroll, is for the panel that expands when btn1 is clicked, btnAct is just for a css that change the color of the button while the panel is expanded. For now, I've put click(), like a bandaid.

resizeWindow = (windowPixel) => {
  const {chatScroll, btn1Act} = initialState;

  if (windowPixel !== this.state.windowPixel) {
    if (windowPixel === false) {
      if (this.state.isSigned) {
        document.getElementById('btn1').click();
        this.setState({chatScroll, btn1Act});
      }
    }
    this.setState({windowPixel});
  }
};

原因很简单兄弟首先单击您的对象或函数或变量,无论它是什么,只需在第一次单击时初始化,当您第二次单击时,它将按照您的代码工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM