如何在 story 渲染完成后派发自定义事件给面板

解读

面试官真正想确认的是:

  1. 你是否理解 Storybook 的“双上下文架构”(预览 iframe vs 面板 Addon 上下文)。
  2. 你是否掌握通道通信机制(Channel API),因为两个上下文之间不能直接用 DOM 事件或全局变量,必须通过 @storybook/channels 做安全隔离。
  3. 你是否能把“渲染完成”这一时机精确对齐到 React/Vue 的生命周期,避免“事件早发”或“内存泄漏”。
  4. 你是否能把事件收敛到 Story 级别,而不是污染全局,体现组件库工程化思维。

国内很多候选人在回答时只说“用 addEventListener”或“emit 一下”,却忽略了 iframe 隔离、通道注册时机与清理,直接被判定为“只看过文档,没做过工程”。

知识点

  1. Channel API:import { addons } from '@storybook/addons' 提供的 addons.getChannel() 是唯一跨上下文通信总线。
  2. 预览端事件:Storybook 在渲染完 story 后会自动派发 STORY_RENDERED(常量 @storybook/core-events)。
  3. 自定义事件约定:为了避免与官方事件冲突,事件名必须加命名空间,例如 myOrg:customReady。
  4. 清理义务:在 story 卸载(或切换)时,必须在 useEffect 返回函数里执行 channel.removeListener,否则会造成重复监听 + 内存泄漏。
  5. 面板端消费:Addon 面板里用 useChannel(或 addons.getChannel().on)监听,再把数据同步到本地状态,即可实现实时日志、性能指标、可视化调试等高级功能。

答案

  1. 在 .storybook 目录下新建 addons.js(或 manager.js)注册自定义面板:
import { addons } from '@storybook/addons';
import { AddonPanel } from '@storybook/components';
import React, { useEffect, useState } from 'react';

const ADDON_ID = 'myOrg/custom';
const PANEL_ID = `${ADDON_ID}/panel`;

const CustomPanel = () => {
  const [payload, setPayload] = useState(null);
  useEffect(() => {
    const channel = addons.getChannel();
    const handler = (data) => setPayload(data);
    channel.on('myOrg:customReady', handler);
    return () => channel.off('myOrg:customReady', handler);   // 严格清理
  }, []);
  return <div>收到自定义数据:{JSON.stringify(payload)}</div>;
};

addons.add(PANEL_ID, {
  type: addons.types.PANEL,
  title: '自定义事件',
  render: ({ active }) => (active ? <CustomPanel /> : null),
});
  1. 在组件 story 里精准等待渲染完成再发事件:
import { useEffect } from 'react';
import { addons } from '@storybook/addons';
import { STORY_RENDERED } from '@storybook/core-events';

export default {
  title: 'Example/Button',
  component: Button,
};

export const Primary = (args) => {
  useEffect(() => {
    const channel = addons.getChannel();
    // 必须等官方 STORY_RENDERED 触发后再发,保证 DOM 已挂载
    const handler = () => {
      channel.emit('myOrg:customReady', { timestamp: Date.now(), msg: '渲染完毕' });
    };
    channel.once(STORY_RENDERED, handler);
    return () => channel.off(STORY_RENDERED, handler);   // 清理,防止多次绑定
  }, []);

  return <Button {...args} />;
};
  1. 运行 npm run storybook,切换故事后可在“自定义事件”面板实时看到数据,完全隔离、零全局污染、可复用。

拓展思考

  1. 性能埋点:把上述 timestamp 换成 performance.getEntriesByName() 即可在面板侧生成首屏组件渲染耗时报表,方便设计走查。
  2. 双向通信:面板也可以 channel.emit('myOrg:updateProps', newProps),预览侧监听后动态重渲染 story,实现“无代码调试”。
  3. 多框架兼容:Vue 用户可在 onMounted 里发事件,Angular 用户可在 ngAfterViewInit 里发事件,通道代码完全不变,凸显 Storybook 的框架无关优势。
  4. CI 集成:在 Chromatic 或自建流水线中,通过 storybook-addon-custom-events 把事件日志序列化到 __events.json,可做回归断言:“本次 PR 是否导致组件少发了某个关键事件”。

掌握这套模式后,你不仅回答了“如何发事件”,更展示了工程化、可维护、可扩展的组件库治理思路,国内一线大厂技术终面会立即加分。