Storybook 的 action() 仅在由事件直接调用时才有效

cro*_*ill 1 javascript storybook

我正在使用 Storybook 的action()在组件上创建事件侦听器。

这似乎有效:

import { action } from '@storybook/addon-actions';

...

<custom-link-component>
  <a 
    href="https://google.com"
    onBlur={action('blur')}
  >
    Google
  </a>
</custom-link-component>
Run Code Online (Sandbox Code Playgroud)

Storybook 在“操作”窗格中记录事件。然而,代码有点奇怪,因为它action()调用的,而不是传递的,这不是事件通常的工作方式。这可能稍后会有意义。

这不起作用,因为该操作未记录在故事书中:

import { action } from '@storybook/addon-actions';

...

<custom-link-component>
  <a 
    href="https://google.com"
    onBlur={(e) => {console.log(e); action('blur');}}
  >
    Google
  </a>
</custom-link-component>
Run Code Online (Sandbox Code Playgroud)

唯一的区别是action()在匿名函数内部调用。console.log()然而,射击正确。

我怀疑我在这里遗漏了一些基本的东西,我只是不确定是什么。为什么action('blur')在第一个示例中调用?为什么action('blur')在第二个示例中似乎不起作用?

Nic*_*ick 9

action('blur')它本身返回一个事件处理程序,因此您现在需要将事件传递给它:

<a 
  href="https://google.com"
  onBlur={(e) => {
    console.log(e);
    action('blur')(e);
  }}
>
  Google
</a>
Run Code Online (Sandbox Code Playgroud)