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