參數
觀看影片教學
參數是一組關於故事的靜態、已命名的元數據,通常用於控制 Storybook 功能和附加元件的行為。
可用的參數列在參數 API 參考中。
例如,讓我們透過參數自訂背景附加元件。我們將使用 parameters.backgrounds
來定義選取故事時背景工具列中出現的背景。
故事參數
我們可以使用 CSF 匯出上的 parameters
鍵,為單一故事設定參數
Button.stories.ts|tsx
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { Meta, StoryObj } from '@storybook/your-framework';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
component: Button,
};
export default meta;
type Story = StoryObj<typeof Button>;
export const OnDark: Story = {
// 👇 Story-level parameters
parameters: {
backgrounds: {
default: 'dark',
},
},
};
元件參數
我們可以使用預設 CSF 匯出上的 parameters
鍵,為元件的所有故事設定參數
Button.stories.ts|tsx
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { Meta, StoryObj } from '@storybook/your-framework';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
component: Button,
// 👇 Meta-level parameters
parameters: {
backgrounds: {
default: 'dark',
},
},
};
export default meta;
type Story = StoryObj<typeof Button>;
export const Basic: Story = {};
全域參數
我們也可以透過 .storybook/preview.js
檔案的 parameters
匯出,設定所有故事的參數(這是您設定所有故事的檔案)
.storybook/preview.ts
// Replace your-renderer with the renderer you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-renderer';
const preview: Preview = {
parameters: {
backgrounds: {
values: [
{ name: 'light', value: '#fff' },
{ name: 'dark', value: '#333' },
],
},
},
};
export default preview;
設定全域參數是設定附加元件的常見方式。使用背景時,您可以設定每個故事都可以渲染的背景清單。
參數繼承規則
全域、元件和故事參數的組合方式是
- 更具體的參數優先(因此故事參數會覆寫元件參數,而元件參數會覆寫全域參數)。
- 參數會被合併,因此鍵只會被覆寫,永遠不會被捨棄。
合併參數非常重要。這表示可以基於每個故事覆寫單一特定子參數,但仍保留大部分全域定義的參數。
如果您正在定義依賴參數的 API(例如附加元件),最好將此行為納入考量。