Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
reaccionar cambiar el color de un solo elemento con índice

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> &nbsp; <button className="days-btn" style={{ backgroundColor: buttonColor }} color={buttonColor} onClick={handleColorChange} > T </button> </div> );
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;

Zona de pruebas de código

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!