React.js:在服务器端呈现时不触发handleSubmit或onClick

时间:2014-10-01 21:10:39

标签: javascript node.js express reactjs

我在服务器端呈现所有内容并触发handleSubmit时出现问题。这是源代码:

index.js:

module.exports = require('./app/server');

应用程序/服务器/ index.js:

'use strict';

var env = process.env.NODE_ENV || 'development';
var express = require('express');
var http = require('http');
var app = express();

app.set('state', {});


// Inject Config
require('../config/server')[env](app, express);

// Inject component rendering
require('node-jsx').install({extension: '.jsx'});
app.use(require('../../lib/renderReactComponent')(app));

// Start server
var server = http.createServer(app);
return server.listen(app.get('port'), function() {
  return console.log('Listening on port ' + app.get('port') + ', Env: ' + app.settings.env);
});

module.exports = app;

LIB / renderReactComponent.js:

var ReactApp = require('../app');
var React = require('react');
var path = require('path');
var url = require('url');

module.exports = function(app) {
  return function(req, res, next) {
    try {
      var path = url.parse(req.url).pathname;
      res.send(React.renderComponentToStaticMarkup(ReactApp({path: path, state: app.get('state')})));
    } catch(err) {
      return next(err)
    }
  }
}

应用程序/ index.js:

var ReactApp = require('./components/app');
module.exports = ReactApp;

应用/组件/ app.js:

/**
 * @jsx React.DOM
 */

var React = require('react');
var ReactRouter = require('react-router-component');

var App = React.createClass({

  propTypes: {state: React.PropTypes.object.isRequired},

  getInitialState: function() {
    return {items: [], text: ''};
  },

  handleSubmit: function () {
    console.log("handleSubmit triggered!");
    var $author         = this.refs.author.getDOMNode(),
        $text           = this.refs.text.getDOMNode(),
        author          = $author.value.trim(),
        text            = $text.value.trim();

    if(!author || !text) {
        return false;
    }

    if(this.props.onCommentSubmit) {
        this.props.onCommentSubmit({ author: author, text: text });
    }

    $author.value = '';
    $text.value = '';

    return false;
  },

  render: function() {
    return (
      <html>
            <form className="commentForm" onSubmit={this.handleSubmit}>
                <input type="text" ref="author" placeholder="Your name"/>
                <input type="text" ref="text" placeholder="Say Something ..."/>
                <input type="submit" value="Post"/>
            </form>
      </html>
    );
  }
});
module.exports = App;

此代码不会给我一个错误,但不会触发handleSubmit。我认为这是因为它不是由服务器端呈现的。在尝试从服务器端渲染页面时,如何触发表单事件handleSubmit?

1 个答案:

答案 0 :(得分:6)

流程的工作原理如下:

  • 客户请求页面
  • 服务器执行React.renderComponentToString并将html返回给客户端
  • 此时服务器停止执行任何操作
  • 页面加载客户端,并运行React.renderComponent
  • React通过反应注意到标记
    • 验证校验和
    • 如果一切顺利,只需添加事件监听器并等待发生的事情
  • 用户可以提交表单,调用handleSubmit

在handleSubmit中,如果您想将一些数据发送到服务器,您可以使用常规的AJAX / WebSockets / etc技术来完成。

查看superagent以查找适用于浏览器和节点的优质http客户端。