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

126
Views
cómo revertir (el último elemento de la lista en el que se hizo clic) a su color original cuando se hace clic en cualquier otro elemento - ganchos de reacción

Estoy tratando de implementar esta función en reaccionar:

Estado predeterminado: todos los elementos de la lista son azules;

Si se hace clic en un elemento específico: el color del texto del mismo elemento se vuelve rojo;

Cuando se hace clic en cualquier otro elemento: el color del texto del último elemento vuelve a ser azul;

En mi código, el color del texto del elemento permanece rojo, incluso cuando se hace clic en otros elementos.

Busqué aquí y parece que debería usar useRef y item.id, pero no sé cómo implementar esta función en particular.

Gracias

Aplicación.js

 import { useState } from 'react' import Item from './components/Item' function App() { const [items, setItems] = useState([ { id: 1, name: 'Item 1', }, { id: 2, name: 'Item 2', }, ]) return ( <> {items.map((item) => ( <Item key={item.id} id={item.id} name={item.name} /> ))} </> ) } export default App

Artículo.jsx

 import { useState } from 'react' function Item({ id, name }) { const [clicked, setClicked] = useState(false) const handleClick = () => { setClicked(!clicked) } return ( <> <button onClick={handleClick} style={{ color: clicked ? 'red' : 'blue' }} key={id} > {name} </button> </> ) } export default Item
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debe mantener la identificación seleccionada en el componente principal y, en función de la selección, podemos cambiar el color del texto del botón.

Aplicación.jsx

 import { useState } from 'react' import Item from './components/Item' function App() { const [items, setItems] = useState([ { id: 1, name: 'Item 1', }, { id: 2, name: 'Item 2', }, ]) const [selectedId,setSelectedId] = useState(null) return ( <> {items.map((item) => ( <Item key={item.id} id={item.id} name={item.name} handleClick={() => setSelectedId(item.id)} clicked={selectedId === item.id} /> ))} </> ) } export default App

Artículo.jsx

 function Item({ id, name, clicked, handleClick }) { return ( <button onClick={handleClick} style={{ color: clicked ? 'red' : 'blue' }} key={id} > {name} </button> ) }
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!