React元素未呈现/ React Setup问题

时间:2018-06-17 21:07:58

标签: reactjs

在设置webpack和babel两天后,我正在努力学会做出反应。最后,我正在尝试运行一些示例代码。我试图从我的react元素打印一些字符串,并且无法使这个元素工作。

我确实得到了来自HTML的“Hello World”,没有反应的编译错误,所以我可以验证客户端 - 服务器设置是否运行良好。

但是,不会渲染react元素。

以下是三个文件设置。

组件/ homepage.js

"use strict";

var React = require('react');

var Home = React.createClass({
    render: function () {
        return (
        <div className="jumbotron">
            <h1>PluralSight Adminstrator</h1>
            <p>React, React Router, and Flux for ultra responsive website</p>
        </div>
        );
    }
});

module.exports = Home;

和index.js

const jquery = $ = require('jquery');
const Home = require('./components/homepage');
const ReactDOM = require('react-dom');
ReactDOM.render(<Home/>, document.getElementById('app'));

和index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="index.js"></script>

</head>
<body>
    <div id="app"></div>
    Hello World.:)
</body>
</html>

webpack.config.dev.js

const webpack = require('webpack');
const path = require('path');

module.exports = {
    debug: true,
    devtool: 'inline-source-map',
    noInfo: false,
    entry: [
        'eventsource-polyfill', // necessary for hot reloading with IE
        'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails.
        path.resolve(__dirname, 'src/index')
    ],
    target: 'web',
    output: {
        path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
        publicPath: '/',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'src')
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ],
    module: {
        loaders: [
            {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
            {test: /(\.css)$/, loaders: ['style', 'css']},
            {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
            {test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
            {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
            {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}
        ]
    }
};

1 个答案:

答案 0 :(得分:2)

以下代码应该有效(替换主组件代码):

var Home = class Home extends React.Component {
    render() {
        return (
        <div className="jumbotron">
            <h1>PluralSight Adminstrator</h1>
            <p>React, React Router, and Flux for ultra responsive website</p>
        </div>
        );
    }
}

根据docs,如果您想使用create-react-class,则需要使用NPM安装软件包,并按如下所示进行安装:

var createReactClass = require('create-react-class');

编译器可能不会显示错误,但浏览器的控制台必须显示错误。

参考小提琴:https://jsfiddle.net/69z2wepo/194263/