我对React和。jsx文件混合快速路由感到非常困惑。我试图建立一个多页网站与猫鼬数据库,我一直在使用ejs来做到这一点。现在我正试图转换到React,但我完全不知道如何做到这一点,尽管我研究了3天。我希望做的大致是这样的(示例是一个react组件"example.jsx")
app.get("/",function(req,res){ res.send(<example />)})
不是
app.get("/",function(req,res){ res.send("another.ejs") })
如果我不能这样做,你会推荐React路由或者只是坚持使用js吗?
你需要(1.)将JSX代码转换为Javascript,然后(2.)将Javascript渲染成HTML字符串,然后您可以将其发送到客户端。
。如果你有example.js
:
console.log('jsxData:', <example />);
// app.get("/",function(req,res){ res.send(<example />)})
1。将JSX转换为Javascript
如果一个Javascript文件包含JSX代码,它就变成了一个JSX文件,Javascript就不能再理解它了。扩展名。js或。jsx在这里并不重要。您可以也可以不将其重命名为example.jsx
,如果您喜欢的话。
但是你可以转换(也就是。"transpile")的JSX文件到一个Javascript文件与babel。您将得到一个新的,独立的文件,这是一个有效的Javascript文件。
1.。如果还没有安装,你需要安装babel和JSX转译器(这里我使用yarn, npm也可以):
yarn add @babel/cli @babel/core @babel/preset-react --dev
1. b。将JSX文件转换为Javascript:
yarn babel example.js --presets=@babel/preset-react --out-dir dist
现在您应该有新文件/dist/example.js
,这是一个有效的Javascript文件(但仍然不是HTML文件)。(该文件的扩展名将是.js
,无论原始源文件是.js
还是.jsx
。)
2。渲染HTML
在步骤1中。您已经将原始文件中的JSX代码<example />
翻译成已翻译文件中的Javascript代码React.createElement("example", null)
,但这仍然不是HTML,这是Javascript的"React元素"。
你可以使用ReactDOMServer来渲染这个React元素到HTML:
2.。如果还没有安装,那么安装react
和react-dom
:
yarn add react react-dom
2. b。导入react
和react-dom/server
,并使用renderToString()
方法将React元素呈现为HTML字符串:
const React = require('react'); // <-- React is required, because it is used in the transpiled .js file.
const ReactDOMServer = require('react-dom/server');
const jsxData = <example />;
const htmlString = ReactDOMServer.renderToString( jsxData );
console.log('htmlString:', htmlString);
// app.get("/",function(req,res){ res.send( htmlString )})
像以前一样再次编译这个JSX文件。现在在./dist/example.js
中,htmlString
应该包含可以发送到客户端的HTML字符串。在这个例子中,如果你运行e.g.node ./dist/example.js
,你应该看到控制台输出:
htmlString: <example data-reactroot=""></example>