You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sitecore NextJS动态占位符重复ID问题求助

问题描述

我需要动态生成5、10或15个占位符,已创建键为text-container-{*}的占位符,将其添加到Rendering并设置参数模板为继承自IDynamicPlaceholder的渲染参数。我的NextJS代码如下:

interface ComponentProps {
  rendering: ComponentRendering & { params: ComponentParams };
  params: ComponentParams;
}
const array: number[] = [1, 2, 3, 4, 5]; // 生成5个占位符

const TextOrgContainer = (props: ComponentProps): JSX.Element => {
return (
    <div>
      {array?.map((item, key) => {
        const phKey = `text-container-${props.params.DynamicPlaceholderId}`;
        return <Placeholder key={key} name={phKey} rendering={props.rendering} />;
      })}
    </div>
  );
};

目前生成了5个占位符,但所有占位符ID均为text-container-3,导致添加渲染组件到其中一个后,所有占位符都会显示该组件。尝试使用props.params.EnabledPlaceholders但始终返回undefined;若将${props.params.DynamicPlaceholderId}替换为${item},则出现错误:

A rendering error occurred: Cannot read properties of undefined (reading 'attributes').

解决方案

1. 重复ID问题根源

你用props.params.DynamicPlaceholderId作为占位符后缀,这是整个容器组件的动态占位符ID,不是每个子占位符的唯一标识,所以循环生成的所有占位符共用同一个ID,导致内容同步显示。

2. 修复占位符命名逻辑

改用循环变量item作为后缀生成唯一占位符名称,同时要确保Sitecore后端已配置对应数量的text-container-{n}占位符(如text-container-1至text-container-5),否则会触发属性未定义错误。修改后的代码:

const TextOrgContainer = (props: ComponentProps): JSX.Element => {
  // 可通过参数动态控制生成数量,比如从props.params读取配置值
  const placeholderCount = props.params.PlaceholderCount || 5;
  const array = Array.from({ length: placeholderCount }, (_, i) => i + 1);

  return (
    <div>
      {array?.map((item) => {
        const phKey = `text-container-${item}`;
        return <Placeholder key={item} name={phKey} rendering={props.rendering} />;
      })}
    </div>
  );
};

3. 后端配置验证

  • 确认Rendering参数模板已继承IDynamicPlaceholder,且在占位符设置中添加了text-container-{*}作为允许的占位符键。
  • 若使用EnabledPlaceholders参数,需在Sitecore内容编辑器中给该Rendering组件的参数手动添加允许的占位符列表(如text-container-1,text-container-2,...),否则props.params.EnabledPlaceholders会返回undefined。

4. 属性未定义错误原因

当直接用${item}但后端未配置对应占位符时,Sitecore无法找到该占位符的配置属性,因此抛出Cannot read properties of undefined (reading 'attributes')错误,核心是后端缺少对应占位符的定义。

内容的提问来源于stack exchange,提问作者Anthony Fernandes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:52:48