如何使用React.js在Sails.js上渲染服务器端模板? [英] How to use React.js to render server-side template on Sails.js?

查看:108
本文介绍了如何使用React.js在Sails.js上渲染服务器端模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Sails.js和React构建一个同构应用程序.客户端部分很容易.但是我在服务器端渲染时遇到了问题.

I am trying to build an isomorphing app with Sails.js and React. Client-side part is easy. But I run into problems with server-side rendering.

当我尝试使用React服务器渲染一个* .jsx文件时,我得到了:

When I try to server-render an *.jsx file with React, I got this:

renderToString(): You must pass a valid ReactElement

我正在使用sailsjs,react和sails-hook-babel(用于ES6语法).

I am using sailsjs, react and sails-hook-babel (for ES6 syntax).

./assets/components/Auth.jsx:

./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:

./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结合使用).

I have tried both ES5/ES6 syntax everywhere. Error occurs everytime. At clientside this Auth.jsx works fine (I am using webpack with babel-loader).

推荐答案

您的问题不在于组件本身,而是您从模块中导出它的方式.

Your problem isn't with your component itself, it's how you're exporting it from your module.

仅使用 export 时,您需要像这样导入模块.

When using just export you need to import your module like this.

import {Auth} from 'auth';

只需使用 export 即可从您的模块中导出1件以上的东西.

Just using export allows for exporting more than 1 thing from your module.

// 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 .

or you can use import * from 'myModule'; This is called a named export.

您的用例所要使用的是 export default 的使用,它允许从模块中导出单个对象.

What your use case begs for is the use of export default which allows a single object to be exported from your module.

export default class Auth extends React.Component {}

因此,您可以将模块导入为没有花括号的单个对象.

Thus letting you import your module as a single object without curly braces.

import Auth from 'auth';

然后,您需要使用JSX语法 React.renderToString(< Auth/>); React.createElement(Auth);

Then you need to render using either use JSX syntax React.renderToString(<Auth />); or React.createElement(Auth);

您可以在此处

这篇关于如何使用React.js在Sails.js上渲染服务器端模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆