溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

詳解react服務(wù)端渲染(同構(gòu))的方法

發(fā)布時(shí)間:2020-10-19 03:59:51 來(lái)源:腳本之家 閱讀:133 作者:dudeyouth 欄目:web開(kāi)發(fā)

學(xué)習(xí)react也有一段時(shí)間了,使用react后首頁(yè)渲染的速度與seo一直不理想。打算研究一下react神奇服務(wù)端渲染。

react服務(wù)端渲染只能使用nodejs做服務(wù)端語(yǔ)言實(shí)現(xiàn)前后端同構(gòu),在后臺(tái)對(duì)react組件進(jìn)行解析并生成html字符串后返回視圖頁(yè)面。

后臺(tái)為什么可以解析react組件?因?yàn)镹ode.js是一個(gè)Javascript運(yùn)行環(huán)境,nodejs與javascript語(yǔ)法基本是相同的,所以nodejs可以正常解析react組件。

一、準(zhǔn)備動(dòng)作

 1、安裝nodejs與安裝express

安裝nodejs教程:https://www.jb51.net/article/33086.htm

安裝express教程:https://www.jb51.net/article/36710.htm

 2、安裝node-jsx(使nodejs支持jsx語(yǔ)法)

$ npm install node-jsx

3、安裝ejs模板引擎

$ npm install ejs

4、選用ejs模板引擎解析html視圖文件(配置express框架應(yīng)用的app.js),需修改配置如下:

var ejs = require('ejs');
 app.engine('.html',ejs.__express);  //使用ejs模板引擎解析html視圖文件
 app.set('view engine', 'html');  

二、具體實(shí)現(xiàn)如下:

express路由:

"use strict";
var express = require('express');
var router = express.Router(); require("node-jsx").install();  //安裝"node-jsx",安裝該模塊可以使nodejs兼容jsx語(yǔ)法
var React=require("react");
var Com=require('../component/test.js').Component //引入react組件
router.get('/', function(req, res, next) {
 var html=React.renderToString(Com({name:"dudeyouth"}))  //向組件傳參,并使用renderToString方法解析成html字符串
 res.render("index",{component:html}); //渲染到界面
});
module.exports = router;

react組件:

"use strict";
var React=require("react");
var Component=React.Component;
class Test extends Component{
  render(){
    return <h2>{this.props.name}</h2>;
  }
}
module.exports={"Component":function(props){
  return <Test {...props}/>
}};

視圖(使用了ejs模板引擎):

<html>
  <head>
    <title>DudeYouth博客</title>
    <meta charset="utf-8" />
    <link href="css/index.css" rel="external nofollow" rel="stylesheet"/>
    <link href="css/style.css" rel="external nofollow" rel="stylesheet"/>
  </head>
  <body>
  <div id="container"><%-component%></div> <!--使用ejs模板解析后的html字符串-->
  </body>
</html>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI