【问题标题】:React using script that is imported in head使用在 head 中导入的脚本进行反应
【发布时间】:2021-03-26 09:18:49
【问题描述】:

大家好,我正在尝试使用react 制作拼图网站。我找到了一个名为snapfit.js 的库,它可以从png 文件生成简单的拼图。问题是我需要让这个脚本在react component 中工作。

目前我在index.html 中导入snapfit.js 文件,当我在chrome 中打开控制台时,我可以看到snapfit 已添加到窗口中(snapfit.window)。不过,我似乎找不到在我的反应组件中使用它的方法。

目前我有:

import * as React from 'react'
import mole from '../assets/mole.png'
import {Helmet} from 'react-helmet'
import Button from 'react-bootstrap/Button'

export class PuzzelSnapfit extends React.Component {

  render(){
    return (
      <div>
        <h2>Demonstration</h2>
        <div><img src={mole} onLoad={alert(this)} />

        </div>
      </div>
    );
  }
}

export default PuzzelSnapfit

我也尝试过像这样使用 react-helmet:

<div><img src={mole} onLoad={window.snapfit.add(this)} />

当我尝试以这种方式执行它时,我得到一个toUpperCase of undefined 错误,所以这似乎是undefined。我也尝试将图像加载到状态,但随后我也收到 undefined 错误。

任何帮助都将不胜感激,因为我真的不知道我还能尝试什么,除了可能将一个 html 文件注入到我的组件中,但这也有其缺点。

【问题讨论】:

  • 我想知道您的 React 组件和图像是否在 snapfit 之前加载。你可以添加一个事件监听器:“window.addEventListener('load')”然后尝试在你的组件中做一些事情吗?您可以使用 componentDidMount 生命周期
  • 嘿@meesVDS 你找到解决方案了吗?

标签: javascript html reactjs jsx


【解决方案1】:

您可以使用 import 语句将外部脚本导入到您的 react js 文件中。

示例(您要在其中使用snapFitFunction1()snapFitFunction2() 的文件):

import * as React from 'react'
import mole from '../assets/mole.png'
import {Helmet} from 'react-helmet'
import Button from 'react-bootstrap/Button'
import { snapFitFunction1, snapFitFunction2 } from './snapfit.js';
...

在您的 snapfit.js 文件中,您应该有一个用于 snapFitFunction1 和 snapFitFunction2 的导出语句。

示例(snapfit.js):

function snapFitFunction1() {
  console.log('Foo');
}

function snapFitFunction2() {
  console.log('Bar');
}


export snapFitFunction1;
export snapFitFunction2;

您可能必须从 snapfit.js 文件中为要使用的函数添加导出。

【讨论】:

  • 看来snapfit的原作者压缩了他的代码什么的,因为snapfit.js不包含导出,只包含一个大的eval()
  • 您可以将该 eval() 函数打包成一个新函数 const myfunction = () =&gt; { eval( ... ) };,然后导出 myfunction
【解决方案2】:

您可以像这样调用 componentDidMount 中的外部库而不是 React 头盔:

const snapJs = (yourScriptPath) => {
    const script = document.createElement("script");
    script.src = yourScriptPath
    script.async = true;
    document.body.appendChild(script);
}


componentDidMount () {
snapJs("snapfit.js")
}

如果您更喜欢使用 React Helmet,那么这将是正确的方法:

import {Helmet} from "react-helmet";
const PuzzelSnapfit = props => (
<div>
    <Helmet>
       <script src="snapfit.js" type="text/javascript" />
    </Helmet>
</div>
  
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    相关资源
    最近更新 更多