事件处理程序在React + Webpack + Node SSR中不起作用

时间:2018-06-07 16:44:14

标签: javascript node.js reactjs webpack serverside-rendering

为什么 onClick = {this.handleCheck} 在NodeJS中“束缚”之后在以下应用程序中不起作用?但是,我没有看到任何错误,页面显示正确。 当我在没有SSR的情况下启动它 - 一切都很好。

提前感谢您的帮助。

使用React + NodeJS

index.js代码:

import express from 'express';
import http from 'http';

var app = express();

http.createServer(app).listen(3000, function(){
  console.log('Express server listening on port 3000');
});

import { renderToString } from 'react-dom/server';
import React, { Component } from "react";

const Html = ({ body }) => `
  <html>
    <body>
      <div id="app">${body}</div>
    </body>
  </html>
`;

class App extends Component {

  constructor(props){
    super(props);
    this.handleCheck = this.handleCheck.bind(this);
    this.state = {counter: 0}
  }

  handleCheck () {
    console.log('check');
    this.setState({counter: this.state.counter + 1})
  }

  render() {
    return (
        <button onClick={this.handleCheck}>Already clicked {this.state.counter} times!</button>
    );
  }
}

app.get('/',
    function (req, res, next) {
            const body = renderToString(<App/>);
            res.send(Html({body}));
    });

webpack.config.js代码:

const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const path = require('path');

const outputDirectory = "../dist";

module.exports = {
  entry: './src/server/index',
  output: {
    path: path.resolve(__dirname, outputDirectory),
    filename: 'bundle.js'
  },
  target: 'node',
  externals: nodeExternals(),
  module: {
    rules: [
      {
        test: /\.jsx?/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          "presets": ["env", "react"]
        }
      }
    ]
  }
};

0 个答案:

没有答案