[英]Isomorphic ReactJS - how to share code for both server side and client side?
I use express.js and react.js for a small test. 我使用express.js和react.js进行小测试。 Below is my react code:
下面是我的反应代码:
views/Todo.jsx, views / Todo.jsx,
var React = require('react');
var TodoApp = React.createClass({
getInitialState: function() {
return {
counter: 0
};
},
increment: function() {
this.setState({ counter: this.state.counter+1 });
},
render: function() {
return (<div>
<div>{this.state.counter}</div>
<button onClick={this.increment}>Increment!</button>
</div>);
}
});
module.exports = TodoApp;
But the counter
is never increased when the button is clicked. 但是单击该按钮时
counter
永远不会增加。 the increment
function is never been called. increment
函数从未被调用过。
Why? 为什么? What have I done wrong?
我做错了什么?
EDIT: 编辑:
The HTML output on my browser: 我的浏览器上的HTML输出:
<html><head></head>
<body><div class="container">
<div>0</div>
<button>Increment!</button>
</div>
</body>
</html>
As you can see that there is no js in the html header at all. 如您所见,html头中根本没有js。 Is it becos of this?
这是becos吗? I render the HTML with react.js on the server side.
我在服务器端使用react.js渲染HTML。
app.js app.js
var express = require('express');
var reactViews = require('express-react-views');
var app = express();
// View engine setup.
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', reactViews.createEngine());
// Set root.
app.use(express.static(__dirname + '/views'));
// Get routes.
var todo = require('./routes/todo');
// Respond with "todo" app on the todo page.
app.use('/todo', todo);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
routes/router.js 路由/router.js
var express = require('express');
var router = express.Router();
router.get('/', function (request, response) {
response.render('Todo', {}); // 'Todo' is 'views/Todo.jsx'
});
module.exports = router;
I think the problem is the react is not shared between client side and the server side. 我认为问题是客户端和服务器端之间没有共享反应。 currently it works on server side only.
当前它仅在服务器端起作用。 how and what can I do so that it is shared and it works on client side as well?
我如何以及如何做才能使其共享并且也可以在客户端使用?
Any ideas? 有任何想法吗?
我认为它工作正常,请检查以下小提琴
[https://jsfiddle.net/56ppsy4v/][1]
<button onClick={this.increment}>Increment!</button>
应该
<button onClick={this.increment.bind(this)}>Increment!</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.