繁体   English   中英

React - 从外部脚本设置组件 state

[英]React - Set component state from external script

我有 React 项目,我想向应用程序添加外部脚本:

<script async src="https://geowidget.easypack24.net/js/sdk-for-javascript.js"></script>
<link rel="stylesheet" href="https://geowidget.easypack24.net/css/easypack.css"/>

并调用方法:

<script type="text/javascript">
window.easyPackAsyncInit = function () {
    easyPack.init({});
    var map = easyPack.mapWidget('easypack-map', function(point){
        console.log(point);
    });
};
</script>

<div id="easypack-map"></div>

我是这样做的:

componentDidMount() {
    const script1 = document.createElement("script");
    script1.src = "https://geowidget.easypack24.net/js/sdk-for-javascript.js";
    script1.async = true;
    document.body.appendChild(script1);

    const script2 = document.createElement("script");
    script2.type = 'text/javascript';
    script2.async = true;
    script2.innerHTML = "window.easyPackAsyncInit = function () {easyPack.init({});var map = easyPack.mapWidget('easypack-map', function (point) {console.log(point);});};";
    document.body.appendChild(script2);
}

它正在工作,但我想在我的组件中使用 function 返回值point (将其用作组件状态)

选项 1从另一个脚本调用:只需将 this.setState 暴露this.setState上的一个方法并调用该方法将更新它的 state


componentDidMount() {
  window.setPoint = (point)=>this.setState('point',point)
}

// open console and run setPoint(xxx) and check the UI change

选项 2调用公开方法并像您一样从 react 调用,但情况可能会更好

<script async src="https://geowidget.easypack24.net/js/sdk-for-javascript.js"></script>
<link rel="stylesheet" href="https://geowidget.easypack24.net/css/easypack.css"/>

你可以将这些添加到你的模板<head>标签,html文件或webpack中的html插件,添加脚本可能会导致重复

那么你只需要

componentDidMount() {
    easyPack.init({});
    var map = easyPack.mapWidget('easypack-map', (point)=>{
        console.log(point);
        this.setState('point',point)
    });

好的,我找到了解决方案。 在function中设置window.point,然后在Component中读取window.point

script2.innerHTML = "window.easyPackAsyncInit = function () {easyPack.init({});var map = easyPack.mapWidget('easypack-map', function (point) {window.point = point);});};";

但这是最好的解决方案吗?

暂无
暂无

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

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