简体   繁体   English

React 不在 DOM 上渲染任何东西

[英]React not rendering anything on the DOM

I have just started learning ReactJS and made my first app by following a tutorial but nothing is rendered on the screen when I run the html file.我刚刚开始学习 ReactJS 并按照教程制作了我的第一个应用程序,但是当我运行 html 文件时,屏幕上没有呈现任何内容。

index.js index.js

import React from "react"
import ReactDOM from "react-dom"

ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"));

index.html索引.html

<html>
    <body>
        <div id="root">
        </div>
    </body>
    <script type="text/babel" src="index.js"></script>
</html>

Here I think you need to write your code in the form of function which would be called from the HTML file.在这里,我认为您需要以 function 的形式编写代码,该代码将从 HTML 文件中调用。

So you need to update your index.js to:因此,您需要将 index.js 更新为:

import React from "react"
import ReactDOM from "react-dom"

window.printHello = function(id){
   ReactDOM.render(
   <h1>Hello, world!</h1>,
   document.getElementById(id)
   );
 }

And your html file should be updated to the below code:您的 html 文件应更新为以下代码:

<div id="hello"></div>
<script src="index.js"></script>
<script>
 printHello('hello');
</script>

Here is another solution for your query.这是您查询的另一种解决方案。 There is no need to add the script tag in your HTML.无需在 HTML 中添加脚本标签。

If the js and HTML are part of the same component you can just use the id directly in the HTML.如果 js 和 HTML 是同一组件的一部分,您可以直接在 HTML 中使用 id。 So your updated code for js and HTML would be be somewhat like this.所以你更新的 js 和 HTML 代码会有点像这样。

import React from "react"
import ReactDOM from "react-dom"

ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"));

And the HTML code:和 HTML 代码:

<html>
<body>
    <div id="root">
    </div>
</body>
</html>

I hope this would be helpful to you.我希望这对你有帮助。

For me the issue was ReactDOM getting imported from different module.对我来说,问题是ReactDOM从不同的模块导入。 After updating the import statement from更新导入语句后

import ReactDOM from "react";

to

import ReactDOM from 'react-dom/client';

in index.js file worked.index.js文件中工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM