簡體   English   中英

如何使用 React.js 在 Sails.js 上渲染服務器端模板?

[英]How to use React.js to render server-side template on Sails.js?

我正在嘗試使用 Sails.js 和 React 構建一個同構應用程序。 客戶端部分很容易。 但是我遇到了服務器端渲染的問題。

當我嘗試使用 React 服務器渲染一個 *.jsx 文件時,我得到了這個:

renderToString(): You must pass a valid ReactElement

我正在使用sailsjs、react 和sails-hook-babel(用於ES6 語法)。

./assets/components/Auth.jsx:

import React from 'react';

export class Auth extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className='auth'>
        Very simple element without any logic just for test server-rendering.
      </div>
    );
  }
}

./api/controllers/AuthController.js:

var Auth = require('./../../assets/components/Auth.jsx');
import React from 'react';

module.exports = {
    render: function (req, res) {
    //var markup = React.renderToString(
    //  Auth
    //); // This throws an error

    console.log(Auth); // {__esModule: true, Auth: [Function: Auth]}

    //res.view("layout", {app: markup});
  }
};

我到處都嘗試過 ES5/ES6 語法。 每次都會出現錯誤。 在客戶端,這個 Auth.jsx 工作正常(我使用 webpack 和 babel-loader)。

您的問題不在於您的組件本身,而在於您如何從模塊中導出它。

僅使用export您需要像這樣導入模塊。

import {Auth} from 'auth';

僅使用export可以從模塊中導出 1 個以上的東西。

// My Module.
export function a(x) {
    console.log('a');
}

export function b(x, y) {
    console.log('b');
}

import { a, b } from 'myModule';

或者你可以使用import * from 'myModule'; 這稱為命名導出

您的用例要求使用export default ,它允許從您的模塊中導出單個對象。

export default class Auth extends React.Component {}

因此,您可以將模塊作為單個對象導入而無需花括號。

import Auth from 'auth';

然后你需要使用 JSX 語法React.renderToString(<Auth />);進行渲染React.renderToString(<Auth />); React.createElement(Auth);

您可以在此處閱讀有關 ECMA Script 6 中模塊如何工作的所有信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM