我正在尝试将SQLjs脚本端口 of SQLite纳入react中。sql.js包的基本用法很好,如下所示:
<html>
<head>
<style>
table { border-collapse: collapse; width:100%; }
table, th, td { border: 1px solid black; text-align:left; font-family:Arial,Helvetica}
th { color:white;background-color:green}
th, td { padding:4px; }
</style>
</head>
<body>
<script src="https://kripken.github.io/sql.js/js/sql.js"></script>
<h1>SQL Demo</h1>
<div id="results">
</div>
<script>
//Create the database
var db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE employees (id integer, name varchar(50), salary float);");
// Insert two rows: (1,111) and (2,222)
db.run("INSERT INTO employees VALUES (?,?,?), (?,?,?), (?,?,?)", [1,'will',111.55, 2,'sam', 222.25, 3,'mary', 333.99]);
// Prepare a statement
var stmt = db.prepare("SELECT id, name, salary, round(salary) AS rounded_salary FROM employees ORDER BY salary DESC");
stmt.getAsObject({$start:1, $end:4}); // {col1:1, col2:111}
// Bind new values
stmt.bind({$start:1, $end:2});
var output = '<table>';
output += '<tr><th>ID</th><th>Name</th><th>Salary</th><th>Rounded salary</th></tr><tbody>';
while(stmt.step()) { //
var row = stmt.getAsObject();
// [...] do something with the row of result
output += '<tr><td>' + row.id + '</td><td>' + row.name + '</td><td>$' + row.salary + '</td><td>$' + row.rounded_salary + '.00</td>';
output += '</tr>';
}
output += '</tbody></table>';
var elem = document.getElementById('results');
elem.innerHTML = output;
</script>
</body>
</html>
但是,当我使用create-react-app创建一个基本应用程序,使用npm install sqljs --save添加模块并使用它时,我无法访问库。我不明白为什么这不管用。它似乎应该--例如,我能够以这种方式使用CodeMirror包react-codemirror,没有任何问题。
这是我所拥有的。在我的App.js中,我说:
import SQLOutput from './SQLOutput';
然后在SQLOutput.js中我说:
import React, { Component } from 'react';
import * as SQL from 'sqljs';
class SQLOutput extends Component {
constructor(props) {
super(props);
this.db = new SQL.Database();
}
}
export default SQLOutput;最终,我们的计划是执行在第一个html文件中看到的查询,但是在这个react组件中,并让它在某个地方呈现结果。
不幸的是,我似乎不能以构造函数的形式访问SQL.Database对象。ES6抱怨Uncaught TypeError: SQL.Database is not a constructor。实际上,您在react调试器中看到的SQL对象与本文顶部简单版本中注入的全局对象有很大不同。
是否不可能使用像sqljs这样的旧库呢?作为一个愚蠢的替代方案,我还试图通过我的index.html文件作为一个普通的旧脚本加载来使用它,但这也不起作用。也许与create-react-app打包东西的方式有关?
任何对此表示赞赏的指针都会对此做出反应。
我的package.json包含:
{
"name": "react-sqljs",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.5.4",
"react-codemirror": "^0.3.0",
"react-dom": "^15.5.4",
"sqljs": "0.0.0-6"
},
"devDependencies": {
"react-scripts": "0.9.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}发布于 2022-06-22 19:42:30
查看下面的示例:https://github.com/sql-js/react-sqljs-demo/blob/master/src/App.js
import initSqlJs from "sql.js";https://stackoverflow.com/questions/43422402
复制相似问题