繁体   English   中英

React.js中的Hello-World安装指南不起作用

[英]Hello-world in reactjs installation guide not working

我对React.js完全陌生,并开始从教程页面学习。

MacOSX Sierra v10.12

在终端中,我做了:

npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start

然后,我将App.js修改为:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

保存App.js后,页面上没有任何显示。 屏幕截图

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <!--
      Notice the use of  in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
  <script type="text/javascript" src="/static/js/bundle.js"></script></body>
</html>

不知道出了什么问题。 请帮忙。 谢谢!

这是您出错的地方:App.js应该是React组件,index.js是实际处理渲染到dom的文件。 这是原始的index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

它正在将App导入为组件并尝试呈现它。 您基本上在App.js中制作了index.js的副本,因为index.js是实际处理初始DOM呈现的对象,所以它破坏了所有内容。

您有两种选择:

将App.js更改为此:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return <h1>Hello, world!</h1>
  }
}

export default App;

或在index.js中复制并粘贴您先前编写的代码。

暂无
暂无

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

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