ReactJS - renderToString() 方法



將 React 元件渲染到 HTML 是一個常見的操作,尤其是在處理伺服器端渲染 (SSR) 時。這可以透過使用 renderToString 方法來實現。

什麼是 renderToString?

React 的 renderToString 函式將 React 元件渲染成 HTML 字串。在伺服器上,它主要用於在將我們的 React 應用提供給客戶端作為初始伺服器響應的一部分之前預渲染我們的 React 應用。這意味著我們的網站載入速度更快,並且更易於搜尋引擎最佳化。

語法

renderToString(reactNode)

引數

reactNode − 要渲染到 HTML 的 React 節點。例如 <App />。

返回值

它返回一個 HTML 字串。

示例

示例 - 問候應用

在這個程式碼中,我們將建立一個名為 Greetings 的 React 元件來顯示簡單的問候訊息。它將使用伺服器端渲染將元件轉換為 HTML 字串並將該字串記錄到控制檯。執行時,我們將看到 Greetings 元件的初始 HTML 表示,其中包含歡迎標題和鼓勵使用 React 進行構建的訊息。

// Import necessary modules
const React = require('react');
const ReactDOMServer = require('react-dom/server');

// Define a component with greetings
const Greetings = () => (
   <div>
      <h1>Welcome to React!</h1>
      <p>Hope you enjoy building with it.</p>
   </div>
);
export default Greetings;

// Render the component to a string
const htmlString2 = ReactDOMServer.renderToString(<Greetings />);

// Log the result
console.log(htmlString2);

輸出

welcome to react

示例 - 計數器應用

在這個應用中,我們將建立一個 React 元件 (Counter),它表示一個帶有遞增按鈕的簡單計數器。它將使用伺服器端渲染將元件轉換為 HTML 字串並將該字串記錄到控制檯。執行時,我們將看到 Counter 元件的初始 HTML 表示,計數為 0。

// Import necessary modules
const React = require('react');
const ReactDOMServer = require('react-dom/server');

// Define a component with a simple counter
class Counter extends React.Component {
   constructor() {
      super();
      this.state = { count: 0 };
   }   
   render() {
      return (
         <div>
            <h1>Counter: {this.state.count}</h1>
            <button onClick={() => this.setState({ count: this.state.count + 1 })}>
               Increment
            </button>
         </div>
      );
   }
}
export default Counter;

// Render the component to a string
const htmlString3 = ReactDOMServer.renderToString(<Counter />);

// Log the result
console.log(htmlString3);

輸出

counter 3 increment

示例 - 伺服器和客戶端

我們可以透過兩種不同的方式使用 renderToString:第一種是在伺服器上,第二種是在客戶端。因此,我們將逐一討論這兩種方式。

在伺服器上

首先,我們將從 'react-dom/server' 中匯入 renderToString 方法。並使用它將我們的 React 應用渲染到 HTML。

import { renderToString } from 'react-dom/server';
const html = renderToString(<App />);

在客戶端

我們需要一個單獨的函式,例如 hydrateRoot,才能使伺服器生成的 HTML 具有互動性。

首先,驗證我們的響應是否包含伺服器渲染的 HTML,並且我們是否包含了在客戶端載入我們的 React 元件和 hydrateRoot 所需的指令碼。

伺服器端渲染 (Node.js/Express)

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './App'; // Import the main React component

const app = express();
app.get('/', (req, res) => {
   
   // Server-side rendering
   const html = renderToString(<App />);
   res.send(`
      <!DOCTYPE html>
      <html>
      <head>
         <title>Server-Side Rendering</title>
      </head>
      <body>
         <div id="root">${html}</div>
         <script src="/client.js"></script>
      </body>
      </html>
   `);
});

app.listen(3000, () => {
   console.log('Server is running on https://:3000');
});

客戶端 (client.js)

import React from 'react';
import { hydrateRoot } from 'react-dom'; // Import hydrateRoot
import App from './App'; // Import the main React component

// Find the root element
const rootElement = document.getElementById('root');

// Hydrate the server-rendered HTML
hydrateRoot(rootElement, <App />);

使用此方法,我們可以實現伺服器端渲染,同時使內容在客戶端具有互動性,結合兩種方式的優點。

侷限性

  • React Suspense 僅部分支援 renderToString。如果元件等待資料,renderToString 會立即傳送其回退內容作為 HTML。

  • 雖然它可以在瀏覽器中使用,但不建議將其用於客戶端應用程式。客戶端渲染有更好的選擇。

總結

renderToString 是一個有用的 React 方法,用於在伺服器端將我們的元件更改為 HTML,從而提高網站效能和搜尋引擎最佳化。請記住,它可能不是客戶端程式碼的最佳選擇。

reactjs_reference_api.htm
廣告
© . All rights reserved.