javascript - 将动态 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>
调用它。
解决方案
在创建反应应用程序时,您应该能够将任何 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>
)
}
}
推荐阅读
- python - 有没有办法在没有循环的情况下引用 Pandas 列中的先前值?
- python - 如何使 `plt.show()` 响应 ctrl-C?
- php - 如何根据 meta_key 检查购物车中产品的重量?
- python - 使用 Python 解析 XML 并创建 excel 报告 - Elementree/lxml
- django - Django qry在获取列表时返回相关ID而不是对象(Message.objects.select_related(“message_from”).filter(message_to = user.user_id).values())
- sql - SQL 获取单独表中相关实体的计数
- python - 在 Anaconda Jupyter Notebook 中安装 BEST 包
- python - 连接上的 Flask-sqlalchemy ORM TypeError
- c - 无法设置进程时钟的时间,我需要一些权限吗?
- python - 带有 python4delphi 的 delphi 应用程序,在 UNIX 计算机上失败,并带有 -> EPyValueError 和消息