Parameters(參數)
觀看影片教學
參數是一組關於 story 的靜態、具名的 metadata(metadata),通常用於控制 Storybook 功能和擴充套件的行為。
可用的參數列於參數 API 參考文件中。
例如,讓我們透過參數自訂 backgrounds 擴充套件。我們將使用 parameters.backgrounds
來定義當 story 被選取時,背景工具列中出現哪些背景。
Story 參數
我們可以透過 CSF 匯出的 parameters
鍵,為單一 story 設定參數
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
鍵,為元件的所有 stories 設定參數
Button.stories.ts|tsx
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { Meta } from '@storybook/your-framework';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
component: Button,
//👇 Creates specific parameters at the component level
parameters: {
backgrounds: {
default: 'dark',
},
},
};
export default meta;
全域參數
我們也可以透過 .storybook/preview.js|ts
檔案的 parameters
匯出,為所有 stories 設定參數(此檔案用於設定所有 stories)
.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;
設定全域參數是設定擴充套件的常見方式。使用 backgrounds,您可以設定每個 story 都可以渲染的背景清單。
參數繼承規則
全域、元件和 story 參數的組合方式如下:
- 更具體的參數優先(因此 story 參數會覆寫元件參數,而元件參數又會覆寫全域參數)。
- 參數是合併的,因此鍵永遠只會被覆寫而不會被捨棄。
參數的合併非常重要。這表示可以在保留大部分全域定義的參數的同時,在每個 story 的基礎上覆寫單一特定的子參數。
如果您要定義依賴參數的 API(例如,擴充套件),最好將此行為納入考量。