我正在尝试将SQLjs emscriptem port SQLite合并到反应中。 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文件中进行查询,但是在这个反应组件中,让它在某处呈现结果。
不幸的是,我似乎无法将SQL.Database对象作为构造函数访问。 React或ES6抱怨Uncaught TypeError: SQL.Database is not a constructor
。实际上,您在调试器中看到的SQL对象与此帖子顶部的简单版本中注入的全局对象有很大不同。
使用像sqljs这样的旧库是否无法以这种方式做出反应?作为一个愚蠢的选择,我也试图通过我的index.html文件使用它作为一个普通的旧脚本加载,这也是行不通的。也许与create-react-app
打包的方式有关?
对于这个反应noob赞赏任何指针。
我的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"
}
}