如何在故事书 v6 中动态改变组件操作中的"args"?



让我们看看我们有一个简单的组件ToggleButton:

const ButtonComponent = Vue.component('ButtonComponent', {
props: {
value: Boolean
},
methods: {
handleClick() {
this.$emit('toggle');
}
},
template: `
<button 
:class="value ? 'on' : 'off'"
@click="handleClick"
>
Toggle
</button>`
});

这个组件的故事:

import ToggleButton from './ToggleButton.vue';
export default {
title: 'ToggleButton',
component: ToggleButton,
argTypes: {
onToggle: {
action: 'toggle' // <-- instead of logging "toggle" I'd like to mutate `args.value` here
}
}
};
export const Default = (_args, { argTypes }) => ({
components: { ToggleButton },
props: Object.keys(argTypes),
template: `
<ToggleButton
:value="value"
:toggle="onToggle"
/>
`
});
Default.args = {
value: false
}

我想要实现的是处理故事中的toggle动作,并通过将类名从.off更改为.on来更改我在Default.args对象中使用的value以更改按钮样式。

我也遇到了同样的问题,几天来一直在寻找,直到我偶然发现了这篇github帖子:https://github.com/storybookjs/storybook/issues/12006

目前在我的React中(我相信vue方法也会类似(,我做了以下事情:

import React from 'react';
import CheckboxGroupElement from '../CheckboxGroup';
import { STORYBOOK_CATEGORIES } from 'elements/storybook.categories';
import { useArgs } from '@storybook/client-api';
export default {
component: CheckboxGroupElement,
title: 'Components/CheckboxGroup',
argTypes: {
onChange: {
control: 'func',
table: {
category: STORYBOOK_CATEGORIES.EVENTS,
},
},
},
parameters: { actions: { argTypesRegex: '^on.*' } },
};
const Template = (args) => {
const [_, updateArgs] = useArgs();
const handle = (e, f) => {
// inside this function I am updating arguments, but you can call it anywhere according to your demand, the key solution here is using `useArgs()`
// As you see I am updating list of options with new state here
console.log(e, f);
updateArgs({ ...args, options: e });
};
return <CheckboxGroupElement {...args} onChange={handle} />;
};
export const CheckboxGroup = Template.bind({});
CheckboxGroup.storyName = 'CheckboxGroup';
CheckboxGroup.args = {
//Here you define default args for your story (initial ones)
controller: { label: 'Group controller' },
options: [
{ label: 'option 1', checked: true },
{ label: 'option 2', checked: false },
{ label: 'option 3', checked: false },
],
mode: 'nested',
};

故事书v7

只是ProlyGeek答案的更新!在Storybook v7上,应该从以下位置导入:
import { useArgs } from '@storybook/addons'

用途依旧!

这是提到它的文档页面https://storybook.js.org/docs/react/writing-stories/args

最新更新