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

如何通过Figma API将Instance或Frame节点转换为Component节点?

能否通过Figma API将Instance/Frame转换为Component?

目前Figma API不支持直接将现有Instance或Frame节点转换为Component——没有提供类似可视化界面「创建组件」的直接转换方法。不过可以通过复制目标节点的内容、属性到新创建的Component的方式,实现等效效果。

实现思路与代码示例

1. 将Frame转换为Component

通过创建空Component,然后把Frame的子节点、样式、位置等属性复制过去:

// 获取选中的Frame节点(假设当前选中了一个Frame)
const targetFrame = figma.currentPage.selection[0];

if (targetFrame.type === 'FRAME') {
  // 创建新的Component节点
  const convertedComponent = figma.createComponent();
  
  // 复制基础属性:位置、尺寸、名称
  convertedComponent.x = targetFrame.x;
  convertedComponent.y = targetFrame.y;
  convertedComponent.name = targetFrame.name;
  convertedComponent.resize(targetFrame.width, targetFrame.height);
  
  // 复制外观样式:填充、描边、圆角等
  convertedComponent.fills = [...targetFrame.fills];
  convertedComponent.strokes = [...targetFrame.strokes];
  convertedComponent.strokeWeight = targetFrame.strokeWeight;
  convertedComponent.cornerRadius = targetFrame.cornerRadius;
  
  // 复制子节点(深拷贝所有子元素)
  const clonedChildren = targetFrame.children.map(child => child.clone());
  clonedChildren.forEach(child => convertedComponent.appendChild(child));
  
  // 可选:删除原Frame节点
  targetFrame.remove();
}

2. 将Instance转换为Component

Instance是基于源Component的实例,若要将其当前状态(含局部修改样式)转换为独立Component,同样需要复制其内容到新Component:

// 获取选中的Instance节点
const targetInstance = figma.currentPage.selection[0];

if (targetInstance.type === 'INSTANCE') {
  const convertedComponent = figma.createComponent();
  
  // 复制位置、尺寸、名称
  convertedComponent.x = targetInstance.x;
  convertedComponent.y = targetInstance.y;
  convertedComponent.name = `${targetInstance.name} (Converted)`;
  convertedComponent.resize(targetInstance.width, targetInstance.height);
  
  // 复制Instance的覆盖样式(确保保留局部修改)
  convertedComponent.fills = [...targetInstance.fills];
  convertedComponent.strokes = [...targetInstance.strokes];
  
  // 复制子节点(Instance的子节点默认锁定,克隆后会解锁)
  const clonedChildren = targetInstance.children.map(child => child.clone());
  clonedChildren.forEach(child => convertedComponent.appendChild(child));
  
  // 可选:删除原Instance节点
  targetInstance.remove();
}

注意事项

  • 属性完整性:上述代码仅复制了常见属性,若Frame/Instance包含约束、布局网格、自动布局等复杂属性,需要额外手动复制对应字段(如constraints、layoutMode等)。
  • 深拷贝限制:clone()方法会复制节点的大部分属性,但部分特殊绑定(如组件变体关联)无法完全保留,转换后可能需要手动调整。
  • 权限要求:插件需要拥有编辑当前页面节点的权限,确保在manifest.json中配置了正确的权限范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:25:09