目前,我在 DOM 中添加元素并在双引号内附加 html,这可能会变得非常混乱且很难阅读,特别是如果你里面有变量,在 React 中你会使用干净的 JSX,有没有办法在普通的 JQuery 脚本或类似 JSX 的东西中使用 JSX?
是的,有两个选项:
模板文本
JSX
模板文本
在现代 JavaScript 中,您可以使用模板文字而不是字符串文字,它们可以包含带有 JavaScript 表达式的占位符:
let counter = 0;
$(`<table class="main">
<tbody>
<tr>
<td>Cell ${counter++}</td>
<td>Cell ${counter++}</td>
</tr>
<tr>
<td>Cell ${counter++}</td>
<td>Cell ${counter++}</td>
</tr>
</tbody>
</table>`).appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
当然,仍然有一些尴尬,但它比字符串文字要好得多。
更多关于 MDN 上的模板文字。
JSX
JSX 不限于 React。它有自己的规范和多种实现,例如jsx-transform
.
例如,这里有一个简单的 Node.js 包装器,使用它来转译文件:
var jsx = require('jsx-transform');
console.log(jsx.fromFile("input.jsx", {
factory: 'be'
}));
如果input.jsx
是:
let counter = 0;
let table =
<table class="main">
<tbody>
<tr>
<td>Cell {counter++}</td>
<td>Cell {counter++}</td>
</tr>
<tr>
<td>Cell {counter++}</td>
<td>Cell {counter++}</td>
</tr>
</tbody>
</table>;
table.appendTo(document.body);
(请注意,这是class="main"
,而不是className="main"
。使用className
是 React 的事情,以避免自 2009 年 ES5 问世以来一直没有问题的问题。
输出将是:
let counter = 0;
let table =
be('table', {class: "main"}, [
be('tbody', null, [
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
]),
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
])
])
]);
table.appendTo(document.body);
请注意 JSX 表达式是如何转换为对工厂函数的调用的(在该示例中be
;React 的工厂函数是React.createElement
(。您所要做的就是提供be
功能并将转换器集成到您的构建链中(jsx-transform
预先烘焙了插入 Browserify 的能力(。
您使用 jQuery 的be
可能如下所示:
function be(tagName, attributes, children) {
const result = $("<" + tagName + "/>");
if (attributes) {
result.attr(attributes);
}
if (children) {
if (Array.isArray(children)) {
for (const child of children) {
result.append(child);
}
} else {
result.append(child);
}
}
return result;
}
使用转换结果的 be 函数的实时示例:
let counter = 0;
let table =
be('table', {class: "main"}, [
be('tbody', null, [
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
]),
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
])
])
]);
table.appendTo(document.body);
function be(tagName, attributes, children) {
const result = $("<" + tagName + "/>");
if (attributes) {
result.attr(attributes);
}
if (children) {
if (Array.isArray(children)) {
for (const child of children) {
result.append(child);
}
} else {
result.append(child);
}
}
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
令人惊讶的是,它真的就是这么简单。