简体   繁体   中英

Can i setState of a react functional component from a external gloabal function present inside script tag?

I have an android app which calls the a function present inside the head of my react page. All i want is to allow the the function to set a state inside the react component

<head>
  <script>
    webViewAndriodInteraction(parm1)
    {
      //Here i want this function to change the state of my react functional component
      //setSomeState(pram)
    }
  </script>
</head>;

function LiveScreen(props) {
  const [somedata, setSomeState] = useState();
  return <h1>someData</h1>;
}

It's probably against some React best practices, but you could do this:

In your component, define an effect that puts your state setter on the window object:

useEffect(() => {
  window.setSomeState = setSomeState;

  return () => {
    window.setSomeState = undefined;
  };
}, []);

And in your webViewAndriodInteraction function:

if (window.setSomeState !== undefined) {
  // call window.setSomeState here
}

You also need to ensure that your call to window.setSomeState is deferred until the function gets defined. So if you're sure it's going to get defined, you could set a timeout or retry the if check a few times with a given delay.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM