
本文详解如何使用 Figma Plugin API 为组件添加可编辑的属性(如 TokenName、TokenColor),并通过 componentPropertyReferences 将其动态绑定到内部文本节点,实现组件实例化时自动填充内容。
本文详解如何使用 figma plugin api 为组件添加可编辑的属性(如 tokenname、tokencolor),并通过 `componentpropertyreferences` 将其动态绑定到内部文本节点,实现组件实例化时自动填充内容。
在 Figma 插件开发中,若需创建可复用、可配置的文档化组件(例如颜色令牌卡片),仅调用 addComponentProperty() 是不够的——它只定义了属性结构,不会自动关联到子节点。关键在于显式建立“属性 ID”与“节点字段”的映射关系,这正是 componentPropertyReferences 的核心作用。
以下是完整、可运行的实现流程:
✅ 正确创建带绑定的组件
// 1. 创建组件主节点
const cardTokenComponent = figma.createComponent();
cardTokenComponent.name = "Card Token";
cardTokenComponent.resize(206, 176);
// 2. 添加组件属性,并捕获返回的唯一 property ID(⚠️ 必须保存!)
const tokenNamePropId = cardTokenComponent.addComponentProperty("TokenName", "TEXT", "");
const tokenColorPropId = cardTokenComponent.addComponentProperty("TokenColor", "TEXT", "");
// 3. 创建子文本节点
const tokenNameNode = figma.createText();
tokenNameNode.characters = ""; // 初始值可为空,由属性驱动
cardTokenComponent.appendChild(tokenNameNode);
const tokenHexNode = figma.createText();
tokenHexNode.characters = "";
cardTokenComponent.appendChild(tokenHexNode);
// 4. 【关键步骤】将属性 ID 绑定到对应文本节点的 `characters` 字段
tokenNameNode.componentPropertyReferences = { characters: tokenNamePropId };
tokenHexNode.componentPropertyReferences = { characters: tokenColorPropId };
? 注意:
componentPropertyReferences是一个对象,键为节点支持的可绑定字段(如"characters"、"fillPaints"等),值为addComponentProperty()返回的字符串 ID —— 不是属性名(如"TokenName")。
✅ 实例化时动态赋值
for (const category in groupedStyles) {
const categoryFrame = figma.createFrame();
categoryFrame.layoutMode = "HORIZONTAL";
categoryFrame.itemSpacing = 48;
for (const style of groupedStyles[category]) {
const instance = cardTokenComponent.createInstance();
// 使用 property ID(非字符串名)设置值
instance.setProperties({
[tokenNamePropId]: style.name,
[tokenColorPropId]: `#${Math.round(style.color.r * 255).toString(16).padStart(2, '0')}${Math.round(style.color.g * 255).toString(16).padStart(2, '0')}${Math.round(style.color.b * 255).toString(16).padStart(2, '0')}`
});
categoryFrame.appendChild(instance);
}
parentFrame.appendChild(categoryFrame);
}
⚠️ 常见错误与最佳实践
- ❌ 错误:直接用属性名(如
"TokenName")作为setProperties()的 key → 导致赋值失败,无报错但不生效。 - ✅ 正确:始终使用
addComponentProperty()返回的 ID(如"prop_abc123")进行读写。 - ? 提示:建议将 property ID 存入 Map 或常量对象,便于维护和类型安全(尤其在大型插件中)。
- ? 参考文档务必精读:
通过以上方式,你创建的 Card Token 组件即可在 Figma 设计器中被用户直接修改 TokenName 和 TokenColor 属性,且所有实例实时同步更新,真正实现「一次定义、多处复用、动态可控」的设计系统工作流。










