safety-eval-service-frontend/.cursor/skills/specs/13-云组件使用规范/05-生命周期钩子/SKILL.md

2.1 KiB

name description
jjb-cloud-component-lifecycle 定义 JJB 云组件生命周期钩子使用规范。在需要 onLoadStart、onLoadEnd、onMounted、onUpdated、onDestroy 回调时查阅。

云组件使用规范

生命周期钩子

onLoadStart / onLoadEnd

用于处理加载状态:

function MyPage() {
  const [loading, setLoading] = React.useState(false);

  return (
    <>
      {loading && <Spin />}
      <CloudComponent
        from="https://example.com/my-component.js"
        componentKey="my-component"
        onLoadStart={() => setLoading(true)}
        onLoadEnd={() => setLoading(false)}
      />
    </>
  );
}

onMounted

组件挂载后调用,可以获取组件引用并调用组件方法:

function MyPage() {
  return (
    <CloudComponent
      from="https://example.com/my-component.js"
      componentKey="my-component"
      onMounted={(key, ref) => {
        console.log(`组件 ${key} 已挂载`);
        
        // 获取组件输出的表单配置
        if (ref.formItems) {
          console.log('表单配置:', ref.formItems);
        }
        
        // 更新组件数据
        if (ref.updateData) {
          ref.updateData(
            { theme: 'dark', language: 'zh-CN' }, // settings
            { items: [1, 2, 3] } // dataSource
          );
        }
      }}
    />
  );
}

onUpdated

组件更新后调用:

function MyPage() {
  return (
    <CloudComponent
      from="https://example.com/my-component.js"
      componentKey="my-component"
      onUpdated={(key, ref) => {
        console.log(`组件 ${key} 已更新`);
        console.log('设置:', ref.settings);
        console.log('数据源:', ref.dataSource);
      }}
    />
  );
}

onDestroy

组件销毁时调用,用于清理资源:

function MyPage() {
  return (
    <CloudComponent
      from="https://example.com/my-component.js"
      componentKey="my-component"
      onDestroy={() => {
        console.log('组件已销毁');
        // 清理相关资源
      }}
    />
  );
}