javascript - 将 JS 脚本转换为 React 组件
问题描述
我一直在尝试在我的反应应用程序中使用这个简单的 javascript 脚本( https://seatchart.js.org/或https://github.com/omarmahili/seatchart.js )。在一个 html 项目中,只需添加脚本并运行它,但我在与 React 框架的集成方面遇到了困难。任何方法建议将不胜感激。
我尝试了一些补丁工作但没有太大成功,即
从我的 react 组件中的脚本调用 JS 函数,但是“let sc = new Seatchart(options);”会引发“'Seatchart' is not defined”错误。
在“let sc = new window.Seatchart(options);”中添加“window”会导致“document.getElementById(options.map.id).appendChild(mapContainer)”出现“Cannot read property 'appendChild' of null”错误。(可能是因为编译器找不到与 html 密切相关且与 React 没有太大关系的“文档”。)
使用 UseRef() 编译,但返回一个空白屏幕...
我下面的失败代码省略了整个 1800 行脚本,我复制粘贴在 React 函数上方以便访问“Seatchart()”。脚本在这里
export default function Tickets () {
let options = {
map: {
id: 'map-container',
rows: 9,
columns: 9,
// e.g. Reserved Seat [Row: 1, Col: 2] = 7 * 1 + 2 = 9
reserved: {
seats: [1, 2, 3, 5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21],
},
disabled: {
seats: [0, 8],
rows: [4],
columns: [4]
}
},
types: [
{ type: "regular", backgroundColor: "#006c80", price: 10, selected: [23, 24] },
{ type: "reduced", backgroundColor: "#287233", price: 7.5, selected: [25, 26] }
],
cart: {
id: 'cart-container',
width: 280,
height: 250,
currency: '£',
},
legend: {
id: 'legend-container',
},
assets: {
path: "../../public",
}
};
let sc = new Seatchart(options);
return (
<div>
<div id="map-container">
</div>
<div id="legend-container">
</div>
<div id="shoppingCart-container">
</div>
</div>
);
} };
从概念上讲,我如何将 JS 脚本集成到我的 React 组件中?
更新:
在公共/index.html 中:
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<script type="text/javascript" src="../src/containers/SeatChart.js" ></script>
<div id="root"></div>
在座位表中:
// SeatChart.js script and Option arg. above, but too long to post...
let sc = new Seatchart(options);
localStorage.setItem("scObj", sc);
localStorage.setItem("test", "this is a test");
console.log("You would see this if SeatChart ran successfully);
在 Ticket.js 中
export default function Ticket () {
const sc = localStorage.getItem("scObj");
console.log(sc);
const test = localStorage.getItem("test");
console.log(test)
return (
<div>
<div>Hello from here!</div>
<div id="map-container">
</div>
<div id="legend-container">
</div>
<div id="shoppingCart-container">
</div>
</div>
);
};
解决方案
请按照以下步骤操作:
- 在根目录下的 react 应用程序中创建一个 js 文件,例如“init.js”,在其中导入所需的脚本。
现在 init.js 应该可以访问 let sc = new Seachart(options)
编写所需的逻辑,并将结果返回/保存/发送到 redux 存储或本地存储。(可以使用store.dispatch()。)
2.只需将上述enter code here
脚本导入您的 react 应用程序的 index.html 文件中。
- 在您的组件中,读取由脚本函数处理的 redux/local-storage 的输出。
推荐阅读
- vuejs2 - 在mounted中设置变量,但在设置变量后不会更改
- powershell - SCCM 未从 powershell 读取返回代码
- sql - 试图在没有否定记录的表中查找唯一记录
- apache-spark - 为什么在 main 方法之外创建的方法不能在 RDD 中运行?
- javascript - Monaco 编辑器 - 使用警告/错误图标自定义 linting 错误
- windows - closesocket 后的 Windows 套接字完成例程回调
- sql-server - OleDbDataReader 和 bulkcopy.WriteToServer 不写入表
- exist-db - 无法加载文档 /LoW.xml。也许它不是有效的 TEI 或不在 TEI 命名空间中?
- python - 如何使用 Python 添加数组
- mysql - sql:sql:query (JSTL) 之后的更新