我有一个呈现以下内容的 React JS 文件:
React.render(
<TreeNode node={tree} />,
document.getElementById("tree")
);
我通过以下方式从 HTML 文件中引用它:
<!doctype html>
<html lang="en">
<link rel="stylesheet" href="app/listTree/treenode.css">
<h3>It's <code>TreeNodes</code> all the way down</h3>
<p>Edit the <code>tree</code> variable to change the tree</p>
<div id="tree">
<script src="/listTree/TreeNode.js"></script>
</div>
</html>
但是,JS文件的内容没有显示。
我没有使用 JavaScript 的经验。 为什么会这样?
最佳答案
您的脚本已经选择了 tree
分区元素。所以,没有必要在 div 标签的 inside 中放置一个 script 标签。
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="app/listTree/treenode.css">
</head>
<body>
<h3>It's <code>TreeNodes</code> all the way down</h3>
<p>Edit the <code>tree</code> variable to change the tree</p>
<div id="tree">
</div>
<script src="listTree/TreeNode.js" type="text/jsx"></script>
</body>
</html>
您还缺少 <head>
和 <body>
html 标签。
此外,如果你想在你的 React 代码中渲染 jsx,你需要添加 <script>
它们的标签(和 type="text/jsx"
作为标签属性):
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="app/listTree/treenode.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
</head>
<body>
<h3>It's <code>TreeNodes</code> all the way down</h3>
<p>Edit the <code>tree</code> variable to change the tree</p>
<div id="tree">
</div>
<script src="listTree/TreeNode.js" type="text/jsx"></script>
</body>
</html>
编辑:
作为确保您的环境正常工作的测试(并且您不只是在组件中遇到问题。尝试将 Treenode.js
中的代码替换为:
React.render(
<div>Testing...</div>,
document.getElementById("tree")
);
然后,您就没有外部依赖项了。如果你看到 Testing...
呈现后,您知道环境设置正确。
关于javascript - React 如何连接 JS 文件和 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737307/