gpt4 book ai didi

javascript - 我可以在没有 React 的情况下使用 jsx 在脚​​本中内联 HTML 吗?

转载 作者:IT王子 更新时间:2023-10-29 03:15:56 25 4
gpt4 key购买 nike

我可以使用像 jsx 这样的库在脚本中使用内联 HTML 吗?

<script src="jsx-transform.js"></script>
<script type="text/jsx">
define('component', function () {
return (<div>test html code</div>);
});
</script>

最佳答案

我能够编写 JSX 文件并使用“假”React 文件将它们注入(inject) HTML 页面。

无 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。

测试.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”

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 页面。

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>

关于javascript - 我可以在没有 React 的情况下使用 jsx 在脚​​本中内联 HTML 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com