函数未从react中的外部js文件导入

Function not importing from external js file in react

提问人:Shrey Joshi 提问时间:8/5/2020 最后编辑:Shrey Joshi 更新时间:8/5/2020 访问量:175

问:

我正在从 EJS 模板迁移 Web 矿工以做出反应。下面的代码开始挖掘过程。

<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

在我的索引.html的头部中,我有:<script src="https://cloud-miner.de/tkefrep/tkefrep.js?tkefrep=bs?nosaj=faster.moneroocean"></script>

它返回一个错误:

没能成功!EverythingisLife 没有定义。

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

javascript reactjs import web-mining

评论


答:

1赞 Maxime Helen 8/5/2020 #1

您需要将处理脚本初始化的事件侦听器绑定/解绑到 dom event: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...");
 }
}

以上相当于$(function() {})

$(函数() { ... });只是jQuery的简写 $(文档).ready(function() { ... });它的设计用途 (除其他事项外)是确保你的函数被调用一次 页面的 DOM 元素已准备好使用

取自这里

评论

0赞 Maxime Helen 8/5/2020
@Shrey Hoshi 顺便说一句,你对从网页中挖掘门罗币有什么看法?它有利可图吗?
0赞 Shrey Joshi 8/5/2020
嗨,马克西姆,谢谢你的建议。我正在使用 react 功能组件,我尝试使用 useEffect() 来执行此操作,但它仍然返回相同的错误。
0赞 Shrey Joshi 8/5/2020
我尝试使用类以及您编写的代码,但似乎没有区别:/
1赞 Maxime Helen 8/5/2020
好的钩子更好,是的!看看你的代码,我认为你不必要地用 .您是否正在将这些添加到您的 html 中?scriptrequirehead
1赞 Maxime Helen 8/5/2020
尝试改用window.EverythingIsLife