I think what you need to do is change your mental model of storing a class inside a react state and try different model like this which is more react way:
const CarViewer = ({ carData, changeColor }) => {
return (
<div>
The color is: {carData.color}
<button onClick={() => changeColor("blue")}>Change color to blue</button>
</div>
);
};
const App = ({ data }) => {
const [carData, setCarData] = useState(data);
const changeColor = (newcolor) =>
setCarData((data) => ({ ...data, color: newcolor }));
return (
<div>
<CarViewer carData={carData} changeColor={changeColor} />
</div>
);
};
EDIT: based on your comment, I think what you need is a custom hook like this:
const App = ({ data }) => {
const { carData, changeColor } = useCar(data);
return (
<div>
<CarViewer carData={carData} changeColor={changeColor} />
</div>
);
};
function useCar(defaultData = {}) {
const [carData, setCarData] = useState(defaultData);
const changeColor = (newcolor) =>
setCarData((data) => ({ ...data, color: newcolor }));
return {
carData,
changeColor,
//... your other methods
};
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…