I am new to react js and I am trying to build an app using it to show the shortest bath, so I defined a graph as a class component containing nodes, every node is also a class component returns an object {isVisited, parent, ...}, and my algorithms must run on this graph. on the other hand I defined components to view the nodes. Now the problem is that I want to restyle the viewed nodes when the graph nodes get visited for example. Note: I tried to solve this problem by using a reference to the div that view a node in the graph nodes, but this way I am making the functional part and the view part intersect, is there any other way like a custom event where the graph node starts is and the view nodes listen to, or something else solves the problem?
if you want a component to perform an action (like change style) whenever a different component changes state you need to somehow add that state as a prop to the first component.
For example, this is a button component that, when pressed, will change the background color of a different component (box):
import React, {useState} from "react";
const Box = () => {
const [backgroundColor, setBackgroundColor] = useState('red');
return(
<div style={{backgroundColor: backgroundColor}}>
<Button setBackgroundColor={setBackgroundColor} />
</div>
);
}
const Button = ({setBackgroundColor}) => {
return (
<div onClick={()=>{setBackgroundColor('blue')}}>
<p>Click me to change the color!</p>
</div>
);
}
Or at least something like this...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.