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

如何在Storybook中为Vue组件的voidNote事件绑定处理函数?

解决方案

1. 遵循React事件命名规范修改Props名

React社区约定组件的事件回调Props采用on[事件名]的驼峰命名格式,这也是你遇到类型错误的核心原因——组件的类型定义里只识别onVoidNote而非voidNote。

首先调整NoteSection组件的Props定义,把事件回调字段改为onVoidNote,同时确保组件内部在接收到子组件冒泡的事件时,正确调用这个回调并传入completeProcessing方法:

// NoteSection.tsx
type NoteSectionProps = {
  // 其他组件Props...
  onVoidNote?: (completeProcessing: () => void) => void;
};

export const NoteSection = ({ onVoidNote, ...rest }: NoteSectionProps) => {
  const handleVoidNote = () => {
    // 定义停止子组件加载的回调函数
    const completeProcessing = () => {
      // 这里写通知子组件停止加载动画的逻辑
    };
    // 调用父级传入的事件处理函数
    onVoidNote?.(completeProcessing);
  };

  return (
    <div onVoidNote={handleVoidNote}> {/* 捕获子组件冒泡上来的事件 */}
      {/* NoteItem列表渲染逻辑 */}
    </div>
  );
};

2. 在Storybook中实现模拟异步处理

在Storybook的故事文件里,直接在args中定义onVoidNote处理函数,用setTimeout模拟异步API调用,调用传入的completeProcessing来停止子组件的加载状态:

// NoteSection.stories.tsx
import { NoteSection } from './NoteSection';

export default {
  component: NoteSection,
  title: 'Components/NoteSection',
};

const Template = (args) => <NoteSection {...args} />;

export const Default = Template.bind({});
Default.args = {
  onVoidNote: (completeProcessing) => {
    // 模拟API调用的异步延迟
    setTimeout(() => {
      console.log('异步操作完成,停止加载动画');
      // 调用回调停止子组件的加载状态
      completeProcessing();
    }, 1500);
  },
};

3. 确认子组件事件传递逻辑

确保NoteItem组件触发事件时,能正确将事件冒泡到NoteSection,比如NoteItem中的触发逻辑:

// NoteItem.tsx
const NoteItem = () => {
  const handleTriggerOperation = () => {
    // 启动自身的加载动画
    // 触发事件并冒泡到父组件
    const event = new CustomEvent('voidNote', { bubbles: true });
    document.dispatchEvent(event);
  };

  return <button onClick={handleTriggerOperation}>触发操作</button>;
};

这样就能在Storybook中正确模拟异步操作流程,同时通过completeProcessing回调停止子组件的加载状态,也彻底解决了之前的类型错误问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 17:52:08