renderToStaticMarkup

renderToStaticMarkup 将一个非交互式的 React 树渲染成 HTML 字符串。

const html = renderToStaticMarkup(reactNode, options?)

参考

🌐 Reference

renderToStaticMarkup(reactNode, options?)

在服务器上,调用 renderToStaticMarkup 将你的应用渲染成 HTML。

🌐 On the server, call renderToStaticMarkup to render your app to HTML.

import { renderToStaticMarkup } from 'react-dom/server';

const html = renderToStaticMarkup(<Page />);

它将生成 React 组件的非交互式 HTML 输出。

🌐 It will produce non-interactive HTML output of your React components.

查看更多示例。

参数

🌐 Parameters

  • reactNode:你想要渲染为 HTML 的 React 节点。例如,一个像 <Page /> 的 JSX 节点。
  • 可选 options:用于服务器渲染的对象。
    • 可选 identifierPrefix:React 用于 useId. 生成的 ID 的字符串前缀。在同一页面上使用多个根时,这有助于避免冲突。

返回

🌐 Returns

一个 HTML 字符串。

🌐 An HTML string.

注意事项

🌐 Caveats

  • renderToStaticMarkup 输出无法被水合。
  • renderToStaticMarkup 对 Suspense 的支持有限。如果一个组件挂起,renderToStaticMarkup 会立即将其回退内容作为 HTML 发送。
  • renderToStaticMarkup 可以在浏览器中使用,但不建议在客户端代码中使用它。如果你需要在浏览器中将组件渲染为 HTML,通过将其渲染到 DOM 节点中来获取 HTML。

用法

🌐 Usage

将非交互式 React 树作为 HTML 渲染为字符串

🌐 Rendering a non-interactive React tree as HTML to a string

调用 renderToStaticMarkup 将你的应用渲染为 HTML 字符串,然后你可以将其随服务器响应发送:

🌐 Call renderToStaticMarkup to render your app to an HTML string which you can send with your server response:

import { renderToStaticMarkup } from 'react-dom/server';

// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const html = renderToStaticMarkup(<Page />);
response.send(html);
});

这将生成 React 组件的初始非交互式 HTML 输出。

🌐 This will produce the initial non-interactive HTML output of your React components.

易犯错误

此方法生成的 HTML 是非交互式的,无法进行水合。 如果你想将 React 用作简单的静态页面生成器,或者渲染完全静态的内容(例如电子邮件),这非常有用。

🌐 This method renders non-interactive HTML that cannot be hydrated. This is useful if you want to use React as a simple static page generator, or if you’re rendering completely static content like emails.

交互式应用应在服务器上使用renderToString,在客户端上使用hydrateRoot

🌐 Interactive apps should use renderToString on the server and hydrateRoot on the client.