附加元件的類型
每個 Storybook 附加元件都分為兩大類:基於 UI 的或預設的。每種附加元件的功能都會在這裡記錄。在建立附加元件時,請以此作為參考。
基於 UI 的附加元件
基於 UI 的附加元件可讓您使用以下元素自訂 Storybook 的 UI。
面板
面板附加元件可讓您在 Storybook 的附加元件面板中新增自己的 UI。這是生態系統中最常見的附加元件類型。例如,官方的 @storybook/actions
和 @storybook/a11y
就使用了這種模式。
使用此樣板程式碼,將新的 Panel
新增至 Storybook 的 UI
addon-panel/manager.js
import React from 'react';
import { AddonPanel } from '@storybook/components';
import { useGlobals, addons, types } from '@storybook/manager-api';
addons.register('my/panel', () => {
addons.add('my-panel-addon/panel', {
title: 'Example Storybook panel',
//👇 Sets the type of UI element in Storybook
type: types.PANEL,
render: ({ active }) => (
<AddonPanel active={active}>
<h2>I'm a panel addon in Storybook</h2>
</AddonPanel>
),
});
});
工具列
工具列附加元件可讓您在 Storybook 的工具列中新增自己的自訂工具。例如,官方的 @storybook/backgrounds
和 @storybook/addon-outline
就使用了這種模式。
使用此樣板程式碼,將新的 button
新增至 Storybook 的工具列
addon-toolbar/manager.js
import React from 'react';
import { addons, types } from '@storybook/manager-api';
import { IconButton } from '@storybook/components';
import { OutlineIcon } from '@storybook/icons';
addons.register('my-addon', () => {
addons.add('my-addon/toolbar', {
title: 'Example Storybook toolbar',
//👇 Sets the type of UI element in Storybook
type: types.TOOL,
//👇 Shows the Toolbar UI element if the story canvas is being viewed
match: ({ tabId, viewMode }) => !tabId && viewMode === 'story',
render: ({ active }) => (
<IconButton active={active} title="Show a Storybook toolbar">
<OutlineIcon />
</IconButton>
),
});
});
索引標籤
索引標籤附加元件可讓您在 Storybook 中建立自己的自訂索引標籤。例如,官方的 @storybook/addon-docs 就使用了這種模式。
使用此樣板程式碼,將新的 Tab
新增至 Storybook 的 UI
addon-tab/manager.js
import React from 'react';
import { addons, types } from '@storybook/manager-api';
addons.register('my-addon', () => {
addons.add('my-addon/tab', {
type: types.TAB,
title: 'Example Storybook tab',
render: () => (
<div>
<h2>I'm a tabbed addon in Storybook</h2>
</div>
),
});
});
瞭解如何在這裡撰寫包含這些 UI 元素的自己的附加元件這裡。
預設附加元件
Storybook 預設附加元件是 babel
、webpack
和 addons
設定的組合,用以整合 Storybook 和其他技術。例如官方的 preset-create-react-app。
在撰寫自己的預設附加元件時,請使用此樣板程式碼。
.storybook/my-preset.js
export default {
managerWebpack: async (config, options) => {
// Update config here
return config;
},
webpackFinal: async (config, options) => {
return config;
},
babel: async (config, options) => {
return config;
},
};
深入瞭解 Storybook 附加元件生態系統