简体   繁体   English

我可以从脚本标签内的外部全局函数中设置反应功能组件的状态吗?

[英]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.我有一个 android 应用程序,它调用我的反应页面头部的一个函数。 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:这可能违反了一些 React 最佳实践,但你可以这样做:

In your component, define an effect that puts your state setter on the window object:在您的组件中,定义一个将您的状态设置器放在window对象上的效果:

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

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

And in your webViewAndriodInteraction function:在你的webViewAndriodInteraction函数中:

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.您还需要确保您对window.setSomeState的调用被推迟到函数被定义为止。 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.因此,如果您确定它会被定义,您可以设置超时或在给定延迟的情况下重试if检查几次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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