React Node 端代码实现

服务端只渲染 HTML 的 HTML,HEAD,BODY 标签结构,具体 BODY 内容由 ctx.renderClient 进行 React 客户端渲染; 文件名为 webpack entry 的文件名,注入的页面 JS 文件为 app/public 文件。

  • ${root}/app/controller/render/render.ts
  1. import { Controller } from 'egg';
  2. export default class ReactController extends Controller {
  3. public async reactClientRender() {
  4. const { ctx } = this;
  5. await ctx.renderClient('react-client-render.js', {
  6. title: 'React Client Render',
  7. text: 'Egg + React + TypeScript + Webpack Client Side Render'
  8. });
  9. }
  10. }
  • ${root}/app/router.ts
app.get('/csr', app.controller.render.reactClientRender);

React Web 端代码实现

${root}/app/web/page/render-client-render/index.tsx

import React, { Component } from 'react';
import { CSR } from '../../framework/app';
class Index extends Component {
  componentDidMount() {
    console.log('client render');
  }
  render() {
    return <h1>{this.props.text}11</h1>;
  }
}
export default CSR(Index);

构建配置实现

${root}/config/res.config.js

module.exports = {
  entry: {
   'react-client-render': 'app/web/page/react-client-render/index.tsx'
  }
}