我可以使用没有React的jsx来在脚本中内联html吗? [英] can i use jsx without React to inline html in script?
本文介绍了我可以使用没有React的jsx来在脚本中内联html吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用像jsx这样的库在脚本中内联HTML:
Can I inline HTML in a script as below by using a library like jsx:
<script src="jsx-transform.js"></script>
<script type="text/jsx">
define('component', function () {
return (<div>test html code</div>);
});
</script>
推荐答案
我能够编写JSX文件并将其注入使用'假'反应文件的HTML页面。
I was able to write JSX files and inject them into an HTML page using a 'fake' React file.
no-react.js
no-react.js
/**
* Include this script in your HTML to use JSX compiled code without React.
*/
const React = {
createElement: function (tag, attrs, children) {
var element = document.createElement(tag);
for (let name in attrs) {
if (name && attrs.hasOwnProperty(name)) {
let value = attrs[name];
if (value === true) {
element.setAttribute(name, name);
} else if (value !== false && value != null) {
element.setAttribute(name, value.toString());
}
}
}
for (let i = 2; i < arguments.length; i++) {
let child = arguments[i];
element.appendChild(
child.nodeType == null ?
document.createTextNode(child.toString()) : child);
}
return element;
}
};
然后编译你的jsx。
Then compile your jsx.
test.jsx
const title = "Hello World";
document.getElementById('app').appendChild(
<div>
<h1>{title}</h1>
<h2>This is a template written in TSX, then compiled to JSX by tsc (the Typescript compiler), and finally
injected into a web page using a script</h2>
</div>
);
结果编译'test.js'
Resulting compiled 'test.js'
var title = "Hello World";
document.querySelector('#app').appendChild(React.createElement("div", null,
React.createElement("h1", null, title),
React.createElement("h2", null, "This is a template written in TSX, then compiled to JSX by tsc (the Typescript compiler), and finally" + " " + "injected into a web page")));
最后,HTML页面包含两个脚本。
And finally, the HTML page that includes both scripts.
index.html
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>no-react</title>
<script src="no-react.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
<script src="test.js"></script>
这篇关于我可以使用没有React的jsx来在脚本中内联html吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文