Tengo una función simple que maneja el estado de varios botones y crea una clase dinámica. Aquí, en mi código, he cambiado con éxito el estado del evento onclick. Quiero cambiar el color de la clase dinámicamente para el evento onclick, pero la clase no cambia. ¿Qué hice mal aquí? He estado luchando con cosas simples
import React, { useEffect, useState } from 'react' function Tes() { const lst = [ { 'name' : 'Python', 'active': true, 'disabled': false }, { 'name' : 'Java', 'active': false, 'disabled': true }, { 'name' : 'PHP', 'active': true, 'disabled': false }, { 'name' : 'C++', 'active': true, 'disabled': false }, { 'name' : 'Javascript', 'active': false, 'disabled': true }, { 'name' : 'Django', 'active': true, 'disabled': false } ] const [statebtn, setStatebtn] = useState(lst) function onClick(key, index) { let tmp = statebtn; tmp[index][key] = !tmp[index][key]; setStatebtn(tmp); console.log(statebtn, 'fsadsada'); } function changeClass(statevalue) { return (statevalue ? "btn-primary" : "btn-danger") } return ( <div> {lst.map((x,index) => ( <button onClick={() => onClick('active', index)} className={`btn ${statebtn[index]['active'] ? "btn-primary" : "btn-danger"}`} disabled={x['disabled']}>{x['name']}</button> )) } </div> ) } export default Tes2 notas mi amigo.
function onClick(key, index) { let tmp = [...statebtn]; // <- this will force the ref to original data to be changed, so mutations will trigger re-rendering. tmp[index][key] = !tmp[index][key]; setStatebtn(tmp); }¡También! Me di cuenta de que no está haciendo un bucle en el estado sino en una matriz codificada. Usa esto en su lugar.
{statebtn.map((x, index) => ( // <- statebtn.map instead of lst.map <button onClick={() => onClick("active", index)} className={`btn ${x["active"] ? "btn-primary" : "btn-danger"}`} disabled={x["disabled"]} > {x["name"]} {x["active"].toString()} </button> ))}La razón por la que no funcionaba era porque estabas haciendo una copia superficial, lo que deberías haber hecho es hacer una copia profunda.
Verifique el código a continuación
function onClick(key, index) { let tmp = statebtn.slice(); tmp[index][key] = !tmp[index][key]; setStatebtn(tmp); console.log(statebtn, 'fsadsada'); }