在 React 的按钮上添加和删除 class

Add & Remove class on button in React

我是 React 的新手,所以这个问题听起来有点问题,但我想不通。所以我有两个按钮,我想在单击其中一个按钮时在它们上面添加 class 。所以按钮必须是默认的 className="button" 并且其中之一被点击它应该被添加到被点击的按钮“selected-button”class。此外,当 Button1 单击时,“selected-button”应该从 Button2 中删除。有时我真的是 React 的新手,简单的事情可能会令人困惑,谢谢你的帮助。

import React, { Component } from "react";
import { Form } from "react-bootstrap";

export class InstantQuote extends Component {
  constructor(props) {
    super(props);
    this.state = {
      active: false,
    };
  }

  toggleClass() {
    const currentState = this.state.active;
    this.setState({ active: !currentState });
  }

  render() {
    const handleSubmit = (e) => {
      e.preventDefault();
    };
    return (
      <Form className="instantquote shadow p-3 mb-5" onSubmit={handleSubmit}>
        <Form.Group controlId="formGroupFrom">
          <div className="selectable-buttons">
            <button type="submit"
            className={((this.state.active) ? "button button-selected": "button")}
            onClick={ () => this.setState({active: !this.state.active}) }>
              Button1
            </button>
            <button type="submit"
            className={((this.state.active) ? "button button-selected": "button")}
            onClick={ () => this.setState({active: !this.state.active}) }>
              Button2
            </button>
          </div>
        </Form.Group>
      </Form>
    );
  }
}

export default InstantQuote;

active 状态变量更改为 activeButton,其中包含活动按钮的标识符(例如名称)。如果您单击一个已经激活的按钮,则将 activeButton 设置为空字符串。

    this.state = {
       activeButton: ""
    }

    const onButtonClick = (buttonName) => 
        setState({...this.state, 
                  activeButton: this.state.activeButtonn === buttonName 
                                ? "" 
                                : buttonName);
    
    render(){
       ...
       <button 
           type="submit"
           className={'button'+ this.state.activeButton === "Button1" && ' button-selected'}
           onClick={ () => onButtonClick("Button1") }>
              Button1
       </button>
       <button type="submit"
           className={'button'+ this.state.activeButton === "Button2" && ' button-selected'}
           onClick={ () => onButtonClick("Button2") }>
              Button2
       </button>
    ...
}

您无法确定哪个按钮处于活动状态,我建议为每个按钮设置一个唯一标识符,并在组件状态下跟踪活动按钮。以下是按钮的声明方式。

this.state = {
  active: ""
}

...
<button
  id="button1"
  className={`button ${this.state.active === "button1" ? "button-selected" : ""}`}
  onClick={ () => this.setState({active: "button1"}) }>
   Button1
</button>

如果您的组件需要可变数量的按钮,请事先声明信息。

const buttons = [{label: "Button1", id: "button1"}, ...];
...
buttons.map(button => 
    <button
      id={button.id}
      className={`button ${this.state.active === button.id ? "button-selected" : ""}`}
      onClick={ () => this.setState({active: button.id}) }>
       {button.label}
    </button>
)