在 Storybook 中制作故事时,Template.bind({}) 中是否需要有 {}

9 reactjs storybook

最近我开始学习React Storybook。在下面的示例中,当我不写入时{}Template.bind({})故事书将运行得很好,不会出现任何错误。但我发现很多人在制作故事时都会使用{}in Template.bind({})

问: Storybook 制作故事时需要有{}内部吗?Template.bind({})

import React from 'react'
import { MyButton } from './MyButton'

export default {
    title :  'MyButton',
    component : MyButton
};

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

export const Primary = Template.bind()
Primary.args = {
    variant: 'primary',
    label: 'button'
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ash 9

不,{}没有必要或不重要。

.bind(thisArg)是一种方法,您可以调用函数来返回一个新函数,并将其this关键字设置为您传递给的任何内容thisArg。但是,在箭头函数上(如您的示例中),您传递的内容并不重要thisArg,因为this箭头函数的工作方式不同。调用.bind()只会返回该函数的新克隆。

.bind()方法在这里仅用于克隆函数Template()。绑定行为并不重要(特别是因为它是一个箭头函数)重要的是,当你这样做时:

export const Primary = Template.bind()
Primary.args = {
    variant: 'primary',
    label: 'button'
}
Run Code Online (Sandbox Code Playgroud)

Primary获得自己的args财产。您将获得该函数的多个克隆Template,并且不会互相干扰。

这是另一个问题的答案.bind(),它更详细地解释了如何使用其方法克隆函数。


daG*_*aGo 1

Template.bind({})是浪费时间/资源,因为它在每次调用时都会创建一个对象,所以基本上是的 -Template.bind()就足够了。如果没有提供任何参数来绑定,则不会发生任何不良情况。