React实现点击按钮切换多按钮样式的需求求助
The problem with your existing code is that you’re relying on a single boolean state (black) which only allows toggling between Button1 being active and the other two buttons being active. This can’t fulfill the requirement where clicking any button should switch it to the blackButton class, while the rest switch to whiteButton.
Here’s how to fix it:
We’ll adjust the state to track the currently active button instead of a simple boolean. This way, we can precisely control which button gets the black styling.
1. Update the Component State
Instead of black: true, use a state variable like currentActiveBtn to store the identifier of the active button (e.g., "btn1", "btn2", "btn3"). Initialize it to "btn1" to match your initial requirement.
2. Modify the changeColor Function
Update this function to accept the button identifier as a parameter, then set currentActiveBtn to that value when a button is clicked.
3. Adjust Button Class Logic
For each button, check if its identifier matches currentActiveBtn—if yes, apply blackButton, otherwise use whiteButton.
4. Update Click Event Bindings
Pass the corresponding button identifier to the changeColor function when each button is clicked.
Modified App.js Code
import React, { Component } from 'react'; import './color.css'; class Test extends Component { constructor(){ super(); // Track the currently active button, start with Button1 active this.state = { currentActiveBtn: "btn1" } } // Accept button ID to set as active changeColor(btnId){ this.setState({ currentActiveBtn: btnId }) } render(){ // Determine class for each button based on active state let btn_class1 = this.state.currentActiveBtn === "btn1" ? "blackButton" : "whiteButton"; let btn_class2 = this.state.currentActiveBtn === "btn2" ? "blackButton" : "whiteButton"; let btn_class3 = this.state.currentActiveBtn === "btn3" ? "blackButton" : "whiteButton"; return ( <div> <button className={btn_class1} onClick={() => this.changeColor("btn1")}> Button1 </button> <button className={btn_class2} onClick={() => this.changeColor("btn2")}> Button2 </button> <button className={btn_class3} onClick={() => this.changeColor("btn3")}> Button3 </button> </div> ) } } export default Test;
Notes:
- Your
color.cssfile doesn’t need any changes—its styling rules are already correct for the classes we’re using. - We’re using arrow functions in the
onClickhandlers to easily pass the button identifier. This avoids issues withthisbinding and makes the code more readable. - This approach scales well too—if you add more buttons later, you just need to add a new identifier and adjust the class logic accordingly.
内容的提问来源于stack exchange,提问作者pratteek shaurya

