简体   繁体   中英

Button with onClick only works once in React

I need to make a collapse menu in a React app, but the button with onClick only works once. I created a boolean variable and it should change when I tap the button. But I can tap the button only once and thereafter the <a> doesn't work, it's inactive:

let isOpened = false;

class Header extends React.Component {
  handleClick = () => {
    isOpened = !isOpened;
  };

  render() {
    const path = history.location && history.location.pathname;
    return (
      <div className={s['header-left']}>
        <div className={s.button}>
          <a href="#"  onClick={this.handleClick}>
            <FontAwesomeIcon icon={faBars} />
          </a>
        </div>

And the collapse code:

<Collapse isOpened={isOpened}>
        <nav className={`${s.menu} ${s.mobile}`}>
          <ul className={s['menu-ul']}>
            ...
          </ul>
        </nav>
      </Collapse>

Your onClick is working fine but it is not re-rendering your react component. You need to put isOpened in the state of the component and global variable. Please read this

class Header extends React.Component {
  constructor(props){
      super(props);

      this.state = {isOpened: false};
  }
  handleClick = () => {
    this.setState({isOpened: !this.state.isOpened});
  };

  render() {
    const path = history.location && history.location.pathname;
    return (
      <div className={s['header-left']}>
        <div className={s.button}>
          <a href="#"  onClick={this.handleClick}>
            <FontAwesomeIcon icon={faBars} />
          </a>
        </div>
   );
 }

Addendum to answer of @Ajay Gaur

Your problem is in the using <a href="#" onClick={this.handleClick}> When you try to click on a link browser want to redirect you to the next page becouse in a you added href="#" . So there are two ways to solve your problem.

1: Use button instead a tag.

2: Add preventDefaul to your method:

handleClick = (e) => {
  e.preventDefault();
  this.setState({ isOpened: !this.state.isOpened });
};

It should to help.

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