首页 文章

ReactDOM没有将React组件呈现为HTML

提问于
浏览
1

我一直在关注React指南,该指南通过在我的仓库中设置webpack和babel . 我创建了一个只会打印出“Hello World”的react元素,然后我使用ReactDOM.render方法将此元素添加到index.html文件中,但由于某种原因它没有被添加 .

这是我的Index.js文件:

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

export default class App extends React.component {
    render() {
        return(
            <div>
              Hello World
            </div>
        )
    }
};
//////EDITED OUT <button /> for <App />
ReactDOM.render(<App />, document.getElementById("root"))

我的index.html文件:

<!DOCTYPE html>
<div id="root"></div>

我的webpack.config.js文件

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: "./App/index.js",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.(js)$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
            { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
        ]
     },
     plugins: [
          new HtmlWebpackPlugin({
              template: 'App/index.html'
          })
      ]
}

我的index.css:

body {
  background: red;
}

我的.babelrc文件

{
  "presets": ["es2015", "react"]
}

我在我的浏览器上检查了开发控制台,它只是没有在index.html文件中显示组件内部的组件 . 我需要ReactDOM将我的react元素推入DOM吗?

我已经在堆栈上查看了其他类似的问题但是他们的问题最终因为一个错字而存在,我已经紧张地看着我的代码并且找不到任何错别字 . 我认为安装中可能有一个步骤我已经跳过了 .

1 回答

  • 2

    你需要渲染 <App /> 而不是 <button />

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    
    export default class App extends React.component {
        render() {
            return(
                <div>
                  Hello World
                </div>
            )
        }
    };
    document.createelement("LI").appendChild(document.createTextNode("Water"));
    ReactDOM.render(<App />, document.getElementById("root"))
    

    你还需要输出它

    /dist/bundle.js

    index.html

    像这样

    <!DOCTYPE html>
    <div id="root"></div>
    <script src="/dist/bundle.js"></script>
    

相关问题