React如何连接JS文件和HTML文件

React how to connect JS file with HTML file

本文关键字:文件 JS HTML 连接 何连接 React      更新时间:2023-09-26

我有一个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的经验。为什么会发生这种情况?

您的脚本已经选择了treediv元素。因此,没有必要在div标签的内放置一个脚本标签

<!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...呈现,您就知道环境设置正确了。

尝试在div后加载脚本,而不是在

<div id="tree">
</div>
<script src="/listTree/TreeNode.js"></script>

你还需要加载React

添加以下脚本

<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>

并将类型更改为'text/babel'

<script type="text/babel" src="script.js"></script>

和外部js文件应该与

.jsx

扩展

请参阅此处的工作示例

你不应该在"listTree"前加斜杠。

所以你的脚本标签应该是这样的:
<script src="listTree/TreeNode.js"></script>