@contentful/experiences-react

中文文档
0.15.9发布于 2026/11/07MITTypeScriptES Module近 30 天下载 4817

内容体验的回放适配器——服务器和客户端渲染器通过便携式渲染器计划

中文使用文档
文档目录13 节
  1. 公共 API
  2. 撰写
  3. 获取
  4. 解析器
  5. 现场预览
  6. 渲染器
  7. 自定义渲染器( E) @contentful/experiences-react/custom-renderer (中…
  8. 样式 + 运行时上下文( 呼)
  9. 再出口类型和公用事业
  10. 快速引用
  11. 间隔儿童
  12. 许可证
  13. 运行时间参数

@ contentful/ 经验 - react

⚠️ 阿尔法. 发布至npm. API是不稳定的,并将改变.

内容体验SDK的回放适配器. 你带来了自己的反应组件;它使经验载荷从经验交付API(XDA)中与之并用.

npm install @contentful/experiences-react

这是你唯一安装的渲染SDK包. 它可以再出口你需要的一切 @contentful/experiences-sdk-core, (中文(简体) ), @contentful/experiences-design,以及 @contentful/experiences-client选项 @contentful/experiences-live-preview 软件包也是客户界面,并提供框架中性活预览客户端.


公共 API

撰写

defineComponent<Props>(config); // Type-narrowing identity for component-type configs
defineExperienceTemplate<Props>(config); // Same shape, for coded Experience Template configs

获取

fetchExperience(experienceOptions, clientOptions, resolveOptions)  // Async; fetches by Destination path/node id or Experience id and resolves in one call
fetchDestinationSitemap(destinationOptions, clientOptions, paginationOptions?) // Async; lists every routable path in a Destination
fetchPreviewSession(previewSessionOptions, clientOptions, resolveOptions) // Async; fetches and resolves a Preview Session Experience
createClient(options)                       // Functional constructor matching the SDK's option shape
ContentfulViewDeliveryClient                // Re-exported delivery client for advanced use cases
NotFoundError                               // Thrown when the Experience ID or Destination path doesn't exist
DestinationPreviewNotSupportedError         // Thrown when preview is requested for a Destination fetch
PreviewSessionFetchError                   // Thrown when fetching a Preview Session fails
LivePreviewConnectionError                 // Reported when the live-preview connection fails
ContentfulViewDelivery                      // Full error namespace from the delivery client
type ExperienceOptions, ByIdExperienceOptions, ByDestinationPathExperienceOptions,
  ByDestinationNodeIdExperienceOptions, DestinationRedirectResult, DestinationSitemapResult,
  FetchDestinationSitemapOptions, FetchDestinationSitemapPaginationOptions, SitemapPathItem,
  PreviewSessionExperienceOptions, PreviewSessionClientOptions,
  PreviewSessionResolveOptions, ClientOptions, ResolveOptions, CreateClientOptions

从目标服务页面: URL 路径是目标路径 。 重定向节点作为值而不是错误返回. 在目标上不支持预览( 它抛出) DestinationPreviewNotSupportedError; 预览时使用代号表.

const result = await fetchExperience(
  { spaceId, destinationId, path: '/demo/landing' },
  { accessToken },
  { config: experienceConfig }
);
if ('redirect' in result) {
  // follow it: navigate to result.redirect.path
}
// otherwise `result` is a PortableRenderPlan

// Enumerate every routable path, for example to prerender
const sitemap = await fetchDestinationSitemap({ spaceId, destinationId }, { accessToken });
const paths = sitemap.items.map((item) => item.path); // follow sitemap.pages.next for more

使用 fetchPreviewSession 内容应用程序时的初始渲染 页:1 preview_session_id预览会话 {\fn黑体\fs22\bord1\shad0\3ahbe\4ah00\fscx67\fscy66\2chffffff\3ch808080}快照并解析成 PortableRenderPlan启用 useLivePreview 改为 接收随后的 WebSocket 更新 :

const plan = await fetchPreviewSession(
  { spaceId, environmentId, sessionId },
  { previewToken },
  { config: experienceConfig }
);

如果预览会话引用了来自其他空格的资源,则通过同样的 编码 resourceResolution 数值 previewSessionOptions 转至 fetchPreviewSession 财务报告和审定财务报表 useLivePreview。 。 。 .

解析器

resolveExperience(payload, config, opts?)   // Async; walks payload, runs resolveData, returns a PortableRenderPlan

现场预览

使用 useLivePreview 当应用程序订阅预览会话更新时, 解决每个有效载荷,并将由此产生的计划从 data数字 :

const livePreview = useLivePreview({
  previewSessionOptions,
  initialPayload,
  initialPlan,
  resolveOptions: { config: experienceConfig },
});

<ClientExperienceRenderer experience={livePreview.data} config={experienceConfig} />;

单独获取原始有效载荷和制作计划,使用 useLivePreviewExperience 财务报告和审定财务报表 useExperiencePlan数字 :

const livePreview = useLivePreviewExperience({
  previewSessionOptions: {
    spaceId,
    environmentId,
    previewToken,
    sessionId,
  },
  initialPayload,
});

const plan = useExperiencePlan({
  payload: livePreview.data,
  initialPlan,
  resolveOptions: { config: experienceConfig },
});

<ClientExperienceRenderer experience={plan.data} config={experienceConfig} />;

useLivePreviewExperience 返回最新的原始有效载荷. initialPayload 种子第一个值. useExperiencePlan 转换有效载荷 输入 PortableRenderPlan 由制造器所消耗并保持电流 正在解决最新情况.

现场审查的结果也暴露了 error 预览会话连接时 失败。 最后一个有效 data 现保留.

渲染器

ServerExperienceRenderer; // RSC-friendly renderer
ClientExperienceRenderer; // Client renderer, alias: ExperienceRenderer
MissingComponent; // Default fallback for unregistered component types

自定义渲染器( E)@contentful/experiences-react/custom-renderer(中文(简体) )

对于自行制定计划而不是使用 ServerExperienceRenderer。 。 。 . resolveNodeProps 返回每个节点的组件并合并道具, ExperienceNode 让它像SDK制造器那样 createExperienceNode 让节点的序列 snapshot 其中组件不能作为道具传递. ServerExperienceRenderer 财务报告和审定财务报表 ClientExperienceRenderer 使每个节点通过相同的 resolveNodeProps + 键 ExperienceNode。 。 。 .

resolveNodeProps(node, config); // ResolvedNode: 'resolved' (component, props, design, contentful, snapshot) | 'unregistered'
ExperienceNode; // Renders one resolved node or snapshot exactly as the SDK renderers do
createExperienceNode(components, experienceTemplates?); // ExperienceNode with its registry bound, for snapshots
type ResolvedNode, NodeSnapshot, ExperienceNodeProps;

样式 + 运行时上下文( 呼)

useDesignValues<T>(); // Escape hatch: the same resolved design record that auto-fills props
toCss(design, options?); // Turns a design record into CSSProperties, keeping only real CSS keys
useExperience(); // RenderContext: debug, metadata
useContentfulComponent(); // Raw payload for the enclosing node (or null), including `attribution`
useContentfulExperienceTemplate(); // Same, for an enclosing coded Experience Template node
getTrackingAttributes(attribution); // Props to spread on a node's outermost element for interaction tracking
type ToCssOptions;

确定的设计值为 自动填入您的组件道具 和内容一起。 这些道具的造型 是推荐的路径. useDesignValues() 揭露出与出逃舱门相同的记录. 仅针对并非登记成分的被窝儿童,或用于在渲染道外所需的设计(一种效应,一种必须测量)——见 样式组件选项 resolveToken 在你身边 Config (单位:千美元)type ResolveToken) (中文(简体) ).

再出口类型和公用事业

// From core
type Config, Components, ExperienceTemplates, Registration, ExperienceTemplateRegistration,
type ComponentConfig, ExperienceTemplateConfig,
type ContentfulComponent, ContentfulExperienceTemplate,
type RenderContext, ResolveToken,
type ExperiencePayload, ExperienceNode, ComponentNode, ExperienceTemplateNode,
type PortableRenderPlan, PortableRenderNode, PortableRegistration,
type DesignPropValue, ManualDesignValue, DesignToken, ExperienceContext, ResolveContext,
type ResolverConfig, ResolveExperienceOptions

// From design
isCssProperty, toCssKey, CSS_PROPERTIES

快速引用

// components/Button.tsx: content + resolved design both arrive as props
'use client';

interface ButtonProps {
  label?: string;
  url?: string;
  backgroundColor?: string; // resolved design, auto-filled
  color?: string;
}

export function Button({ label, url, backgroundColor, color }: ButtonProps) {
  return (
    <a href={url} style={{ background: backgroundColor, color }}>
      {label}
    </a>
  );
}
// lib/experience-config.tsx
import {
  defineComponent,
  type Components,
  type Config,
  type ResolveToken,
} from '@contentful/experiences-react';

import { Button } from './components/Button';

const components: Components = {
  // Bare component, or defineComponent({...}) when you need defaults/resolveData.
  Button: defineComponent({
    resolveData: ({ content }) => ({ url: ensureScheme(content.url) }),
    component: Button,
  }),
};

const resolveToken: ResolveToken = (token) => designTokens[token.value];

export const experienceConfig: Config = { components, resolveToken };
// app/experiences/[id]/page.tsx: in a server component, fetching by Experience id
import { fetchExperience, ServerExperienceRenderer } from '@contentful/experiences-react';

const experience = await fetchExperience(
  { spaceId: process.env.SPACE_ID!, environmentId: 'master', experienceId: id },
  { accessToken: process.env.CDA_TOKEN! },
  { config: experienceConfig }
);
return <ServerExperienceRenderer experience={experience} config={experienceConfig} />;

间隔儿童

每个插槽都是以插槽命名的道具 预交节点数组 (单位:千美元)ReactNode[]由渲染器所键入的——不是单个包接节点. 将数组直接扔入JSX,用于常见的"Just make them"大小写(React make keyed ranges),或 map 编号 : filter 包扎、重排或送小孩.

// components/Section.tsx
import type { ReactNode } from 'react';

export function Section({ children }: { children?: ReactNode[] }) {
  // Common case — render them all:
  return <div>{children}</div>;

  // Or take control of each child:
  // return (
  //   <div>
  //     {children?.map((child, i) => (
  //       <div className="cell" key={i}>{child}</div>
  //     ))}
  //   </div>
  // );
}

children 不是特别的——它只是默认槽的常规名称. 每个 槽被合并为道具,以自己的名义,每个道具作为自己的道具 ReactNode[],所以一个组件有一个 header 位置刚刚宣布 header?: ReactNode[] 并让它同样的方式。 这同样适用于编码的经验模板:带有 content 槽收到一个 content 道具 (英语).

关于全面开始的走过、合并优先规则和设计原理,见 根读取 财务报告和审定财务报表 AGENTS.md。 。 。 .


许可证

麻省理工学院. 见寄存器 LICENSE 财务报告和审定财务报表 NOTICE 完全归属.

运行时间参数

位码 fetchExperience 接受 parameters,例如 { featuredPosts: { limit: 6, order: '-fields.title' } }斯卡拉尔是弦或 数字; 记录叶有一个关卡。 命令是签字的 fields.<apiName> 或者说 sys.<id> 路径。 以已改变的值进行回溯,然后替换出质器的计划. 出口包括 ExperienceParameters, (中文(简体) ), ExperienceParameterValue, (中文(简体) ), ExperienceParameterRecord,以及 ExperienceParameterOrder。 。 。 . 见 收藏/比较示例。 。 。 .

版本与发布记录

@contentful/experiences-react 共发布 69 个版本,首次发布于 2026/07/21;过去 12 个月发布了 69 个版本。

版本发布日期距今
0.15.9latest2026/11/074 天前
0.15.82026/11/055 天前
0.15.72026/11/055 天前
0.15.62026/11/055 天前
0.15.52026/11/046 天前
0.15.42026/10/3111 天前

关于 @contentful/experiences-react 的常见问题

@contentful/experiences-react 是什么?

内容体验的回放适配器——服务器和客户端渲染器通过便携式渲染器计划

如何安装 @contentful/experiences-react?

在项目目录运行 npm install @contentful/experiences-react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.0.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@contentful/experiences-react 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@contentful/experiences-react 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@contentful/experiences-react 可以商用吗?

@contentful/experiences-react 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@contentful/experiences-react 的下载量有多少?

根据 npm 官方下载统计,@contentful/experiences-react 在 2026/10/11 – 2026/11/09 这 30 天内被下载 4,817 次,日均约 161 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@contentful/experiences-react 还在维护吗?

最新版本 0.15.9 发布于 2026/11/07(4 天前);至今共发布 69 个版本,其中过去 12 个月发布了 69 个;首次发布于 2026/07/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。