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

标签 javascript reactjs

我有一个呈现以下内容的 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/

相关文章:

javascript - 使用 Parse Server 返回的数据更新状态后,无法让 React 组件重新渲染

javascript - useState 本身始终是默认值

javascript - react : Number input with no negative, 十进制,或零值

javascript - Heroku buildpack horse 忽略 package.json 中的 Node 版本

javascript - 包含 Div 的部分的 jQuery 选择器

javascript - 如何依次淡出和淡入div

javascript - 匿名 qt 脚本函数的上下文?

javascript - 请简单解释我何时/为什么需要使用 bind()

reactjs - React Router 声明性重定向,同时保留路径的一部分

javascript - 对于大型 json 结构,ReactJS 中的滞后输入