Empecé a aprender a reaccionar hace 2 días y estoy tratando de cambiar el color de un botón al hacer clic. Tengo 2 botones, cada uno de ellos debe cambiar de color cuando se hace clic, sin embargo, mi código cambia el color de ambos cuando solo hago clic en uno. Leí que necesito usar un índice en alguna parte, pero no estoy seguro de dónde o cómo mapear el índice. Cualquier ayuda será muy apreciada. aquí está mi código:
let ash = "#959595"; let purple = "#8c52ff"; const [buttonColor, setButtonColor] = useState(ash); function handleColorChange(e) { const button = e.target.style.backgroundColor; const newButton = e.target.style.backgroundColor; const newColor = buttonColor === ash ? purple : ash; setButtonColor(newColor); } return ( <div> <button className="days-btn" style={{ backgroundColor: buttonColor }} color={buttonColor} onClick={handleColorChange} > M </button> <button className="days-btn" style={{ backgroundColor: buttonColor }} color={buttonColor} onClick={handleColorChange} > T </button> </div> );El problema es que dos botones comparten el mismo estado. Puede mantener la lógica de cambio de color en un componente de Button separado. Entonces los Button pueden cambiar su color de forma independiente.
import { useState } from "react"; let ash = "#959595"; let purple = "#8c52ff"; const Button = ({ buttonText }) => { const [buttonColor, setButtonColor] = useState(ash); function handleColorChange(e) { const newColor = buttonColor === ash ? purple : ash; setButtonColor(newColor); } return ( <button className="days-btn" style={{ backgroundColor: buttonColor }} color={buttonColor} onClick={handleColorChange} > {buttonText} </button> ); }; export default Button;En su otro componente, cree dos botones que proporcionen los accesorios que necesite.
import Button from "./Button"; const App = () => { return ( <div> <Button buttonText="M" /> <Button buttonText="T" /> </div> ); }; export default App;