javascript - Reactjs 安装指南中的 Hello-world 不起作用

标签 javascript html reactjs

我对React.js完全陌生,并开始从tutorial page学习.

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后,页面上没有显示任何内容。 Screenshot

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中复制并粘贴您之前编写的代码。

关于javascript - Reactjs 安装指南中的 Hello-world 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40287974/

相关文章:

javascript - json和绑定(bind)方法

reactjs - 我的 Redux 状态发生了变化,为什么 React 没有触发重新渲染?

javascript - at 符号 (@) 在 React 中用 ES6 和 mixins 做什么?

javascript - 公会加入日期显示为今天的日期,而不是?

javascript - 无法读取 React Native Metro Builder 中未定义的属性 'map'

javascript - 读取 HTML 对象标签中的数据

javascript - 使用变量名 fadeIn 和 Prepend

javascript - 如何重定向到同一路径?

javascript - Socket.IO - socket.on 未运行

javascript - 启动和停止对象移动的按钮