[英]Adding JS script tag to React
I have a script.js file on the server which is written in pure javascript (vanilla) and returns HTML form with some functionality. 我在服务器上有一个script.js文件,该文件使用纯javascript(香草)编写,并返回了具有某些功能的HTML表单。 I download it by first
<script>
tag and use functions from script.js in second <script>
tag in .html file and it is working. 我通过第一个
<script>
标记下载了它,并使用了.html文件中第二个<script>
标记中的script.js中的函数,并且可以正常工作。 But I don't know how to make it run in React. 但是我不知道如何在React中运行它。 I tried to do so, but not working.
我试图这样做,但是没有用。
script.js 的script.js
var lib = lib || (function() { var _args = {}; return { init: function(Args) { _args = Args; }, func: function() { ...some logic and use document.write for render } } }())
In HTML, it works 在HTML中有效
<script src='http://someurl.com/checkout'></script>
<script>
lib.init(...some args);
lib.func();
</script>
In React, it doesn't work 在React中,它不起作用
import React, { Component } from 'react'; import axios from "axios"; class Checkout extends Component { state = {} componentDidMount = async() => { axios.get("http://someurl.com/checkout") .then(res => { const scriptInit = document.createElement("script"); scriptInit.src = "http://someurl.com/checkout"; // or scriptInit.text = res.data; scriptInit.type = "text/javascript"; scriptInit.async = true; const scriptFunc = document.createElement("script"); scriptFunc.text = "lib.init(...); lib.func();"; scriptFunc.async = true; const script = scriptInit.outerHTML + scriptFunc.outerHTML; this.setState({ script }); }) } render() { const __html = this.state.script || ""; return <div id = "checkout" dangerouslySetInnerHTML = { { __html } } /> } } export default Checkout;
Render div tag with all script tags but with 1110 x 0 resolution 渲染具有所有脚本标签但分辨率为1110 x 0的div标签
You need to call the functions after your script loads.You would not need axios for this,you can acheive this using the onload callback for the script load. 您需要在脚本加载后调用这些函数。您不需要axios,您可以使用onload回调来实现此功能来加载脚本。
componentDidMount(){
const script = document.createElement("script");
document.head.appendChild(script);
script.src = "http://someurl.com/checkout";
script.async = true;
script.onload = () => this.runScriptMethods();
}
runScriptMethods(){
lib.init(...);
lib.func()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.