网站搜索

javascript - 除非我将 onClick 添加到 argTypes,否则 Storybook 的 onClick 事件不会被记录


为了在 Storybook 的 Actions 选项卡中记录 onClick 事件,我必须取消注释 SimpleButton.stories.tsx 文件中的 argTypes: { onClick: {} }。我的问题是,为什么我必须这样做?它不能自动推断 onClick 是一个动作吗,因为在 .storybook/preview.js 文件中,parameters 包含属性 actions: { argTypesRegex: "^on[A-Z].*" }?

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
};

简单按钮.tsx

import { VFC } from "react";

interface IProps {
  /** Text to show */
  text: string;
  /** Function to run when button is clicked */
  onClick: () => void;
}

/** This is a very special button component */
const SimpleButton: VFC<IProps> = ({ text, onClick }) => {
  return (
    <button type="button" onClick={onClick}>
      {text}
    </button>
  );
};

export default SimpleButton;

SimpleButton.stories.tsx

import { Meta, Story } from "@storybook/react";
import { ComponentProps } from "react";
import SimpleButton from "../src/components/SimpleButton";

type Props = ComponentProps<typeof SimpleButton>;

const meta: Meta<Props> = {
  title: "SimpleButton",
  component: SimpleButton,
  // argTypes: { onClick: {} } // If I uncomment this onClick action will be logged
};
export default meta;

const Template: Story<Props> = args => <SimpleButton {...args} />;

export const Primary = Template.bind({});
Primary.args = { text: "Click me" };

export const Secondary = Template.bind({});
Secondary.args = { 
  text: "Click me 2",
  onClick: () => { console.log('btn click'); }
};

关于storybook版本,我可以在package.json中看到以下内容

"@storybook/addon-a11y": "^6.5.9",
"@storybook/addon-actions": "^6.5.9",
"@storybook/addon-essentials": "^6.5.9",
"@storybook/addon-links": "^6.5.9",
"@storybook/addons": "^6.5.9",
"@storybook/react": "^6.5.9",
"@storybook/theming": "^6.5.9",

答案#1

我遇到了同样的问题,然后我终止并重新启动了 storybook 服务器,使用 pnpm storybook,现在它可以正常工作了。