首页 > 解决方案 > 将动态 HTML 页面转换为 React/JSX

问题描述

作为一个简单的例子,假设我有这两个文件:

例子.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8" />
    <title>Button example</title>
    <script type="text/javascript" src="ButtonHandler.js"></script>
</head>

<body id="body" onload="init()">
    <button onclick=buttonHandler.writeToConsole()>Button</button>
    <script>

        function init() {
            buttonHandler = new ButtonHandler();
        }
    </script>
</body>

</html>

ButtonHandler.js

function ButtonHandler() {

};

ButtonHandler.prototype.writeToConsole = function () {
    console.log('Writing');
}

每当单击按钮时,这只会打印到控制台。

忽略 ButtonHandler 的构造函数是空的,我可以直接在 onclick 中轻松调用“console.log”。这是我遇到的问题的简化版本,有几个类。

我的问题是,我将如何将其翻译为 React/JSX,理想情况下不修改 Javascript 文件(在这种情况下,只是 ButtonHandler.js)。理想情况下,这意味着没有导出/导入,我想按照 HTML 文件的方式进行操作 - 它只是链接到 <\head> 中的脚本。

我最接近的是这样的:

转换.jsx

import * as React from 'react';   

export default class Entry extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        buttonHandler = new ButtonHandler();
    }

    render() {
        return (
            <div>
                <title>Button example</title>
                <button onclick="buttonHandler.writeToConsole()">Button</button>
            </div>

        )
    }
}

但是我得到了 ButtonHandler 未定义的错误。我按照这个stackexchange 回答并放置

<script type="text/javascript" src="[rest of path...]/ButtonHandler.js"></script>

在公共/索引头中,我在 componentDidMount() 中添加了“window.ButtonHandler”,但我仍然收到未定义的错误。

我做错了什么,如果没有,我还能采取什么其他方法?

编辑:当我将 ButtonHandler.js 放在带有索引的公用文件夹中,并控制台记录窗口时,我看到它显示为窗口的功能,就像 stackexchange 答案描述的那样。但是,当我将它放在另一个文件夹中时,就不会发生这种情况。然而同样的错误。

编辑 2:似乎唯一的解决方案是将 ButtonHandler.js 放在公用文件夹中,然后像所选答案所说的那样在构造函数中调用它。然后添加一个

<button onClick={() => this.buttonHandler.writeToConsole()}>Button</button>

调用它。

标签: javascripthtmlreactjs

解决方案


在创建反应应用程序时,您应该能够将任何 js 文件添加到您的公共文件夹以在您的项目中使用。您只需要引用脚本中的文件,例如:

<script type="text/javascript" src="%PUBLIC_URL%/ButtonHandler.js"></script>

这将确保它在构建时在公共文件夹中查找。

唯一的问题是捆绑包中的文件不会被缩小。

编辑

您还必须引用组件内的全局变量。

/* global ButtonHandler */

import * as React from 'react';   

export default class Entry extends React.Component {
constructor(props) {
    super(props);
  this.buttonHandler = new ButtonHandler();
}

render() {
    return (
        <div>
            <title>Button example</title>
            <button onclick={this.buttonHandler.writeToConsole}>Button</button>
        </div>

    )
  }
}

推荐阅读