工具栏 & 全局变量
观看视频教程
Storybook 附带工具栏插件,用于控制故事渲染的视口和背景。您还可以创建控制特殊“全局变量”的工具栏项。然后,您可以读取全局变量的值以创建装饰器来控制故事渲染。
全局变量
Storybook 中的全局变量表示故事渲染的“全局”(即非特定于故事)输入。由于它们不是特定于故事的,因此不会在故事函数的args
参数中传递(尽管它们可以作为context.globals
访问)。相反,它们通常用于装饰器中,这些装饰器应用于所有故事。
当全局变量发生变化时,故事会重新渲染,并且装饰器会使用新值重新运行。更改全局变量的最简单方法是为它们创建工具栏项。
全局类型和工具栏注释
Storybook 具有一个简单、声明式的语法来配置工具栏菜单。在您的.storybook/preview.js|ts
中,您可以通过创建带有toolbar
注释的globalTypes
来添加您自己的工具栏。
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
const preview: Preview = {
globalTypes: {
theme: {
description: 'Global theme for components',
toolbar: {
// The label to show for this toolbar item
title: 'Theme',
icon: 'circlehollow',
// Array of plain string values or MenuItem shape (see below)
items: ['light', 'dark'],
// Change title based on selected value
dynamicTitle: true,
},
},
},
initialGlobals: {
theme: 'light',
},
};
export default preview;
由于全局变量是全局的,因此您只能在.storybook/preview.js|ts
中设置globalTypes
和initialGlobals
。
启动 Storybook 后,您的工具栏应该会出现一个新的下拉菜单,其中包含light
和dark
选项。
创建装饰器
我们已经实现了global
。让我们将其连接起来!我们可以使用context.globals.theme
值在装饰器中使用新的theme
全局变量。
例如,假设您正在使用styled-components
。您可以将主题提供程序装饰器添加到您的.storybook/preview.js|ts
配置中。
// Replace your-framework with the framework you are using (e.g., solid, qwik)
import { Preview } from '@storybook/your-framework';
import { MyThemes } from '../my-theme-folder/my-theme-file';
const preview: Preview = {
decorators: [
(story, context) => {
const selectedTheme = context.globals.theme || 'light';
const theme = MyThemes[selectedTheme];
return (
// Your theme provider and other context providers go here
)
},
],
};
export default preview;
在故事上设置全局变量
当使用 Storybook 中的工具栏菜单更改全局变量的值时,该值会在您在故事之间导航时继续使用。但有时故事需要特定的值才能正确渲染,例如,在针对特定环境进行测试时。
为了确保故事始终使用特定的全局变量值,而不管在工具栏中选择了什么,您可以在故事或组件上设置globals
注释。这会覆盖这些故事的全局变量值,并在查看故事时禁用该全局变量的工具栏菜单。
// Replace your-framework with the name of your framework
import type { Meta, StoryObj } from '@storybook/your-framework';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
component: Button,
globals: {
// 👇 Set background value for all component stories
backgrounds: { value: 'gray', grid: false },
},
};
export default meta;
type Story = StoryObj<typeof Button>;
export const OnDark: Story = {
globals: {
// 👇 Override background value for this story
backgrounds: { value: 'dark' },
},
};
在上面的示例中,Storybook 将强制所有 Button 故事使用灰色背景颜色,除了OnDark
故事,它将使用深色背景。对于所有 Button 故事,工具栏菜单将被禁用backgrounds
全局变量,并显示一个工具提示,说明全局变量是在故事级别设置的。
配置故事的globals
注释以覆盖项目级全局设置非常有用,但应适度使用。在故事级别未定义的全局变量可以在 Storybook 的 UI 中交互式地选择,允许用户探索所有现有的值组合(例如,全局变量、args
)。在故事级别设置它们将禁用该控件,阻止用户探索可用选项。
高级用法
到目前为止,我们已经在 Storybook 中创建并使用了全局变量。
现在,让我们来看一个更复杂的例子。假设我们想要实现一个名为 **locale** 的新全局变量用于国际化,并在工具栏右侧显示一个旗帜。
在您的 .storybook/preview.js|ts
中,添加以下内容
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
const preview: Preview = {
globalTypes: {
locale: {
description: 'Internationalization locale',
toolbar: {
icon: 'globe',
items: [
{ value: 'en', right: '🇺🇸', title: 'English' },
{ value: 'fr', right: '🇫🇷', title: 'Français' },
{ value: 'es', right: '🇪🇸', title: 'Español' },
{ value: 'zh', right: '🇨🇳', title: '中文' },
{ value: 'kr', right: '🇰🇷', title: '한국어' },
],
},
},
},
initialGlobals: {
locale: 'en',
},
};
export default preview;
示例中使用的 icon
元素从 @storybook/components
包中加载图标。请参阅 此处 以获取您可以使用的可用图标列表。
要使用工具栏,您必须安装 @storybook/addon-toolbars
附加组件,该组件默认包含在 @storybook/addon-essentials
中。
添加配置元素 right
将在您将其连接到装饰器后在工具栏菜单的右侧显示文本。
以下是可用配置选项的列表。
菜单项 | 类型 | 描述 | 必填 |
---|---|---|---|
值 | 字符串 | 设置为全局变量的菜单的字符串值 | 是 |
标题 | 字符串 | 标题的主要文本 | 是 |
右侧 | 字符串 | 在菜单右侧显示的字符串 | 否 |
图标 | 字符串 | 如果选择此项,则在工具栏中显示的图标 | 否 |
在故事中使用全局变量
我们建议在装饰器中使用全局变量,并为所有故事定义全局设置。
但我们也意识到,有时在每个故事的基础上使用工具栏选项更有益。
使用上面的示例,您可以修改任何故事以从故事上下文中检索 **Locale** global
import type { Meta, StoryObj } from '@storybook/react';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
const getCaptionForLocale = (locale) => {
switch (locale) {
case 'es':
return 'Hola!';
case 'fr':
return 'Bonjour!';
case 'kr':
return '안녕하세요!';
case 'zh':
return '你好!';
default:
return 'Hello!';
}
};
export const StoryWithLocale = {
render: (args, { globals: { locale } }) => {
const caption = getCaptionForLocale(locale);
return <p>{caption}</p>;
},
};
在附加组件中使用全局变量
如果您正在开发 Storybook 附加组件,并且需要检索全局变量,您可以这样做。 @storybook/manager-api
包为此场景提供了一个钩子。您可以使用 useGlobals()
钩子来检索任何您想要的全局变量。
使用上面提到的 ThemeProvider 示例,您可以将其扩展到在面板中显示哪个主题处于活动状态,如下所示
import React from 'react';
import { useGlobals } from '@storybook/manager-api';
import { AddonPanel, Placeholder, Separator, Source, Spaced, Title } from '@storybook/components';
import { MyThemes } from '../my-theme-folder/my-theme-file';
// Function to obtain the intended theme
const getTheme = (themeName) => {
return MyThemes[themeName];
};
const ThemePanel = (props) => {
const [{ theme: themeName }] = useGlobals();
const selectedTheme = getTheme(themeName);
return (
<AddonPanel {...props}>
{selectedTheme ? (
<Spaced row={3} outer={1}>
<Title>{selectedTheme.name}</Title>
<p>The full theme object</p>
<Source
code={JSON.stringify(selectedTheme, null, 2)}
language="js"
copyable
padded
showLineNumbers
/>
</Spaced>
) : (
<Placeholder>No theme selected</Placeholder>
)}
</AddonPanel>
);
};
在附加组件中更新全局变量
如果您正在开发需要更新全局变量并刷新 UI 的 Storybook 附加组件,您可以这样做。如前所述, @storybook/manager-api
包为此场景提供了必要的钩子。您可以使用 updateGlobals
函数更新任何您需要的全局值。
例如,如果您正在开发一个 工具栏附加组件,并且希望在用户单击按钮后刷新 UI 并更新全局变量
import React, { useCallback } from 'react';
import { FORCE_RE_RENDER } from '@storybook/core-events';
import { useGlobals } from '@storybook/manager-api';
import { IconButton } from '@storybook/components';
import { OutlineIcon } from '@storybook/icons';
import { addons } from '@storybook/preview-api';
const ExampleToolbar = () => {
const [globals, updateGlobals] = useGlobals();
const isActive = globals['my-param-key'] || false;
// Function that will update the global value and trigger a UI refresh.
const refreshAndUpdateGlobal = () => {
// Updates Storybook global value
updateGlobals({
['my-param-key']: !isActive,
}),
// Invokes Storybook's addon API method (with the FORCE_RE_RENDER) event to trigger a UI refresh
addons.getChannel().emit(FORCE_RE_RENDER);
};
const toggleOutline = useCallback(() => refreshAndUpdateGlobal(), [isActive]);
return (
<IconButton
key="Example"
active={isActive}
title="Show a Storybook toolbar"
onClick={toggleOutline}
>
<OutlineIcon />
</IconButton>
);
};