目前,我使用带有双引号的html附加元素到DOM中,这可能会变得非常混乱和难以阅读,特别是如果其中包含变量,在React中,您可以使用干净的JSX,是否有一种方法在普通的JQuery脚本中或类似JSX的东西中使用JSX?
目前,我使用带有双引号的html附加元素到DOM中,这可能会变得非常混乱和难以阅读,特别是如果其中包含变量,在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并不局限于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);
be
;React的工厂函数是React.createElement
)。您只需要提供be
函数并将转换器集成到构建链中(jsx-transform
预先内置了插入Browserify的功能)。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>