標籤:
1.React.renderToString 函數, 參數是組件,返回一個字串
<!DOCTYPE html><html> <head> <title>React JS</title> <script src="../build_0.13/react.js"></script> <script src="../build_0.13/JSXTransformer.js"></script> <script src="../build_0.13/react-with-addons.min.js"></script> <style type="text/css"> .example-enter{color:red;} .example-active{color:green;} </style> </head> <body> <div id="example" > </div> <script type="text/jsx"> var MyComponent = React.createClass({ render:function(){ return ( <div>Hello World!</div> ); } }); var world = React.renderToString(<MyComponent />); alert(world); console.log(world); </script> </body></html>
2.另一個服務端渲染函數: React.renderToStaticMarkup ,他沒有data屬性
<!DOCTYPE html><html> <head> <title>React JS</title> <script src="../build_0.13/react.js"></script> <script src="../build_0.13/JSXTransformer.js"></script> <script src="../build_0.13/react-with-addons.min.js"></script> <style type="text/css"> .example-enter{color:red;} .example-active{color:green;} </style> </head> <body> <div id="example" > </div> <script type="text/jsx"> var MyComponent = React.createClass({ render:function(){ return ( <div>Hello World!</div> ); } }); //var world = React.renderToString(<MyComponent />); var world = React.renderToStaticMarkup(<MyComponent />); alert(world); console.log(world); </script> </body></html>
兩者在什麼時候使用呢?
若且唯若你不打算在用戶端渲染這個React Component時,才應該選擇使用React.renderToStaticMarkup函數,如:
- 產生html電子郵件
- 通過HTML到PDF的轉化產生PDF
- 組件測試
大多情況下 ,我們都使用React.renderToString()來進行服務端的渲染。
React(0.13) 服務端渲染的兩個函數