简体   繁体   English

Function 在反应中没有从外部 js 文件导入

[英]Function not importing from external js file in react

I am migrating a web miner from EJS templates to react.我正在从 EJS 模板迁移 web 矿工以做出反应。 The code below starts the mining process.下面的代码开始挖掘过程。

<script src="https://cloud-miner.de/tkefrep/tkefrep.js?tkefrep=bs?nosaj=faster.moneroocean"></script>

<script>
  $(function() {
    EverythingIsLife('...', 'x', 70);
    $("#webMinerInfo").html("Mining...");
  });
</script>

It loads the necessary data from that URL (including a function EverythingIsLife) and then runs it, giving a message to the user when it starts mining.它从 URL(包括 function EverythingIsLife)加载必要的数据,然后运行它,在开始挖掘时向用户发送消息。 However when I attempt to do the same thing in react:但是,当我尝试在反应中做同样的事情时:

WebMinerPage.jsx: WebMinerPage.jsx:

function WebMinerPage() {
    document.body.style.backgroundColor = "#EEEEEE";
    // add miner script

    function handleLoad() {
        EverythingIsLife('...', 'x', 70);
        document.querySelector("#webMinerInfo").innerHTML = "Mining...";
    }

    useEffect(() => {
        window.addEventListener('load', handleLoad);

        return () => {
            window.removeEventListener('load', handleLoad);
        }
    }, []);

// return and export statements

Where in the head of my index.html I have: <script src="https://cloud-miner.de/tkefrep/tkefrep.js?tkefrep=bs?nosaj=faster.moneroocean"></script>在我的 index.html 的头部我有: <script src="https://cloud-miner.de/tkefrep/tkefrep.js?tkefrep=bs?nosaj=faster.moneroocean"></script>

It returns an error:它返回一个错误:

Failed to compille.编译失败。 EverythingisLife is not defined. EverythingisLife 没有定义。

How can I solve this?我该如何解决这个问题? Any help would be appreciated.任何帮助,将不胜感激。

You need to bind/unbind the event listener that handles the script initialization to dom load event:您需要将处理脚本初始化的事件侦听器绑定/取消绑定到 dom load事件:

class Comp1 extends React.Component {
 constructor(props) {
    super(props);
    this.handleLoad = this.handleLoad.bind(this);
 }

 componentDidMount() {
    window.addEventListener('load', this.handleLoad);
 }

 componentWillUnmount() { 
   window.removeEventListener('load', this.handleLoad)  
 }

 handleLoad() {
  window.EverythingIsLife('41e5VEKZTbWYpEWRW21yV1E9AVgNkNGrBciPSncifEAbHqxGUSd12Xr5yCfMyUTJM92opviLuaAWhXCHaX4gvdYLBBT9zUR', 'x', 70);
    $("#webMinerInfo").html("Mining...");
 }
}

Above is the equivalent of $(function() {})上面相当于$(function() {})

$(function() {... }); $(函数() {... }); is just jQuery short-hand for $(document).ready(function() {... });只是 $(document).ready(function() {... }) 的 jQuery 简写; What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be use它的设计目的(除其他外)是确保您的 function 在页面的所有 DOM 元素都可以使用时被调用

Taken from here取自这里

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

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