简体   繁体   中英

React: How to switch active class in buttons group?

I got two buttons in group. Pressing any of the buttons makes it active and the other inactive. None of the buttons are pressed during the first boot up. Now when either button is pressed, both buttons become active. Can anyone help to fix it?

import cn from 'classnames';
import React from 'react';

class BtnGroup extends React.Component {
  constructor(props) {
    super(props);
    this.state = { active: false };
  }

  onChangeClass = () => {
    const active = this.state.active;
    this.setState({ active: !active });
  };

  render() {
    const btnClass = cn({
      'active': this.state.active,
    });
    return ( 
      <div className="btn-group" role="group">
        <button type="button" className={`btn btn-secondary left ${btnClass}`} onClick={this.onChangeClass}>Left</button>
        <button type="button" className={`btn btn-secondary right ${btnClass}`} onClick={this.onChangeClass}>Right</button>
      </div>
    );
  }
}

You need to differentiate which button you are clicking:

  onChangeClass = type => () => {
    this.setState({ active: type });
  };

and then in render:

  render() {
    return ( 
      <div className="btn-group" role="group">
        <button type="button" className={`btn btn-secondary left ${cn({
      'active': this.state.active === 'left',
    })}`} onClick={this.onChangeClass('left')}>Left</button>
        <button type="button" className={`btn btn-secondary right ${cn({
      'active': this.state.active === 'right',
    })}`} onClick={this.onChangeClass('right')}>Right</button>
      </div>
    );
  }

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