[英]Event handlers not triggering when rendering reactjs components from nodejs server using express-react-views module
I am using express-react-views package to render react components in serverside(NodeJs). 我正在使用express-react-views包来在服务器端(NodeJs)中呈现反应组件。
I have created my react component. 我已经创建了我的反应组件。 There is a button with an
onClick
event. 有一个带
onClick
事件的按钮。 I have tried to debug the issue but the event is not triggering. 我试图调试问题,但事件没有触发。 How should I fix this issue?
我该如何解决这个问题?
My server.js
file: 我的
server.js
文件:
const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
const router = express.Router();
const cors = require("cors");
const logger = require("morgan");
const { config } = require("./config/config");
const app = express();
app.use(
cors({
origin: "http://localhost:5000",
credentials: true
})
);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + "/views"));
app.set("view engine", "jsx");
app.engine("jsx", require("express-react-views").createEngine());
router.get("/test", (req, res) => {
res.render("test");
});
app.use("/", router);
app.listen(process.env.PORT || 5000, () => {
console.log(`App Started on PORT ${process.env.PORT || 5000}`);
});
My test.jsx
file: 我的
test.jsx
文件:
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: "Initial data..."
};
this.updateState = this.updateState.bind(this);
}
updateState() {
this.setState({ data: "Data updated..." });
}
render() {
return (
<div>
<button onClick={this.updateState}>CLICK</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
export default App;
In test.jsx
file, the onClick
event is not firing. 在
test.jsx
文件中, onClick
事件未触发。 I'm stuck with this issue. 我坚持这个问题。 Please help.
请帮忙。
As evident from the docs - 从文档中可以看出 -
This is an Express view engine which renders React components on server.
这是一个Express视图引擎,它在服务器上呈现React组件。 It renders static markup and does not support mounting those views on the client.
它呈现静态标记,不支持在客户端上安装这些视图。
The library is just meant to render static markup and not support any client side mounting for isomorphic apps. 该库仅用于呈现静态标记,不支持同构应用程序的任何客户端安装。
So basically you're not sending any js to the client ( with React and ReactDOM ) to mount the rendered component on the client and make your eventHandlers work. 所以基本上你不会向客户端发送任何js(使用React和ReactDOM)来在客户端上安装渲染的组件并使你的eventHandler工作。
To solve this, you might want to have a build pipeline ( using webpack, rollup, babel, etc) to bundle up your js files and serve them over a static server. 要解决这个问题,您可能希望拥有一个构建管道(使用webpack,汇总,babel等)来捆绑您的js文件并通过静态服务器提供它们。 Also for server rendering have a look at -> ReactDomServer .
另外对于服务器渲染,请看 - > ReactDomServer 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.