renderToPipeableStream

renderToPipeableStream 将一个 React 组件树渲染为管道化(pipeable)的 Node.js 流

const { pipe, abort } = renderToPipeableStream(reactNode, options?)

注意

这个 API 是专供 Node.js 使用的。像 Deno 这类可以支持 Web 流 的新式非主流运行时环境,应该使用另一个 API renderToReadableStream


参考

renderToPipeableStream(reactNode, options?)

调用 renderToPipeableStream 以 React 组件树渲染为 HTML 后注入 Node.js 流

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

const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});

在客户端,调用 hydrateRoot 以让服务端生成的 HTML 中的绑定事件生效,进而让其变得可交互。

参见下方更多示例

参数

  • reactNode:想要将其渲染为 HTML 的 React 节点,比如像 <App /> 这样的 JSX 元素。这样做意味着整个页面文档都将被渲染,所以这里提到的 App 组件将渲染 <html> 标签.

  • 可选 options:用于配置流的对象.

    • 可选 bootstrapScriptContent:指定一个字符串,这个字符串将被放入 <script> 标签中作为其内容。
    • 可选 bootstrapScripts:一个 URL 字符串数组,它们将被转化为 <script> 标签嵌入页面。请将那些调用了 hydrateRoot<script> 对应的 URL 放入这个数组中。但是如果你不想让客户都端运行 React 的话,请省略这个参数。
    • 可选 bootstrapModules:和 bootstrapScripts 相似,但是嵌入页面的是 <script type="module">
    • 可选 identifierPrefix:一个字符串前缀,用于由 useId 生成的 id。在同一页面下的多人协作场景中会很有用,它能够很好地避免命名冲突。但是注意使用 hydrateRoot 时也要加上同样的前缀。
    • 可选 namespaceURI:一个字符串,指定与流相关联的 命名空间 URI。默认是常规的 HTML。可以传入 'http://www.w3.org/2000/svg' 指定为 SVG,或者传入 'http://www.w3.org/1998/Math/MathML' 指定为 MathML。
    • 可选 noncenonce 一个字符串,能为脚本设置跨域限制,即 script-src 浏览器内容安全策略
    • 可选