I am using function component ,and now I want to pass itself to another objects.
import GlobalParam from './GlobalParam'
const TopPage = (props) =>{
const [load, setLoad] = useState(false);
useEffect(() =>{
GlobalParam.topPage = this;// however it does not work in function component.
})
}
in GlobalParam
export default class GlobalParam {
static topPage;
}
If I can pass conponent function itself to static class,
I can load the topPage from anywhere GlobalParam.topPage.setLoad(true);
What should I use in function component instead of this
?
2
Answers
In function components, you should use useRef instead of this to refer to the component instance. Here’s how you can modify your code to use useRef:
In this code, we are using the useRef hook to create a reference to the component instance. We then pass this reference to the ref attribute of the div element that wraps the component’s code.
In the useEffect hook, we set the topPage property of the GlobalParam class to the current value of the topPageRef reference. Note that we pass an empty dependency array [] to useEffect to ensure that the effect only runs once when the component mounts.
Now, you can access the load state of the TopPage component from anywhere using GlobalParam.topPage.load
Take a look at useContext.
You can define a context with
createContext
(you can specify defaultValue but it’s out of the scope of this example)Then you can wrap your app with a Provider that will make available variables and functions to all its children
and then you can access the context with
useContext
hook!and another component I made just for testing purpose