@ 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。 。 。 .
见 收藏/比较示例。 。 。 .