2016-04-04 113 views
1

我一直在反應幾個月,現在我一直在做服務器端渲染。最近我開始用ES6 + Babel重寫個人應用程序。當我嘗試一個反應組件上運行renderToString()我得到這個錯誤:將反應組件轉換爲字符串時出現錯誤

renderToString(): You must pass a valid ReactElement.

一些代碼

組件

import React from 'react'; 
import ReactDOM from 'react-dom'; 


export class InfoBox extends React.Component { 
    render() { 
     return (
      <div> 
       <div className='info-box'> 
        Hello 
       </div> 
      </div> 
     ); 
    } 
} 

if(typeof window !== 'undefined') { 
    ReactDOM.render(<InfoBox/>, document.getElementById('info-box-mount-point')); 
} 

快遞指數航線

import express from 'express'; 
import React from 'react'; 
import ReactDom from 'react-dom/server'; 
import InfoBox from '../react-components/info-box/info-box.jsx'; 

let router = express.Router(); 
let InfoBoxFactory = React.createFactory(InfoBox); 

/* GET home page. */ 
router.get('/', function(req, res, next) { 
    res.render('index', { 
     reacthtml: ReactDom.renderToString(InfoBoxFactory) 
    }); 
}); 

module.exports = router; 

另一個問題:我是否應該將組件保存爲.jsx.js

回答

2

在這種情況下,你從info-box.jsx需要進口類InfoBox(我在爲HTML組件的渲染方法使用jsx),因爲在info-box.jsx沒有default export

import { InfoBox } from '../react-components/info-box/info-box.jsx'; 
     ^^^  ^^^ 

或添加defaultinfo-box.jsx

export default class InfoBox extends React.Component {} 
     ^^^^^^^ 

更新:

你能避免使用createFactory,只是呈現的反應成分,像這樣

ReactDom.renderToString(<InfoBox />) 
+1

我看到,您的幫助的感謝! –

相關問題