[英]React - Set component state from external script
I have React project and I want to add external script to application:我有 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"/>
and invoke method:并调用方法:
<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>
I did it this way:我是这样做的:
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);
}
It is working, but I want to use function return value point
in my Component (use it as component state)它正在工作,但我想在我的组件中使用 function 返回值
point
(将其用作组件状态)
option 1 call from another script: just expose this.setState
to an method on window and call that method will update it's state选项 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
option 2 call expose the method and call from react as you did, but things can be better选项 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"/>
you can add these into your template <head>
tag, html file or html plugin in webpack, add with script may cause repeats你可以将这些添加到你的模板
<head>
标签,html文件或webpack中的html插件,添加脚本可能会导致重复
then you just need to那么你只需要
componentDidMount() {
easyPack.init({});
var map = easyPack.mapWidget('easypack-map', (point)=>{
console.log(point);
this.setState('point',point)
});
Ok, I found solution.好的,我找到了解决方案。 Set window.point in function and then read window.point in Component
在function中设置window.point,然后在Component中读取window.point
script2.innerHTML = "window.easyPackAsyncInit = function () {easyPack.init({});var map = easyPack.mapWidget('easypack-map', function (point) {window.point = point);});};";
But is it the best solution?但这是最好的解决方案吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.