Storybook 擴充套件 Highlight
Storybook 擴充套件允許您在故事中高亮顯示特定的 DOM 節點。
使用它來吸引對故事特定部分的注意。或者使用它來增強您可能正在構建的其他擴充套件。例如,Accessibility 擴充套件使用它來高亮顯示未通過輔助功能檢查的 DOM 節點。
使用方法
此擴充套件需要 Storybook 6.5 或更高版本。Highlight 是 essentials 的一部分,因此預設安裝在所有新的 Storybook 中。如果您需要將其添加到您的 Storybook,您可以執行以下命令
yarn
yarn add --dev @storybook/addon-highlight
npm
npm install @storybook/addon-highlight --save-dev
pnpm
pnpm add --save-dev @storybook/addon-highlight
將 "@storybook/addon-highlight"
添加到您的 .storybook/main.js|ts
中的 addons 陣列
// .storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
addons: ['@storybook/addon-highlight'],
};
export default config;
高亮顯示 DOM 元素
通過從故事或擴充套件中發出 HIGHLIGHT
事件來高亮顯示 DOM 節點。事件有效負載必須包含一個 elements
屬性,該屬性被分配到與您要高亮顯示的元素相匹配的選擇器陣列。
// MyComponent.stories.ts
import type { Meta, StoryObj } from '@storybook/react';
import { useChannel } from '@storybook/preview-api';
import { HIGHLIGHT } from '@storybook/addon-highlight';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const Highlighted: Story = {
decorators: [
(storyFn) => {
const emit = useChannel({});
emit(HIGHLIGHT, {
elements: ['.title', '.subtitle'],
});
return storyFn();
},
],
};
重設高亮顯示的元素
當故事更改時,高亮顯示會自動清除。您也可以通過發出 RESET_HIGHLIGHT
事件來手動清除它們。
// MyComponent.stories.ts|tsx
import type { Meta, StoryObj } from '@storybook/react';
import { useChannel } from '@storybook/preview-api';
import { HIGHLIGHT, RESET_HIGHLIGHT } from '@storybook/addon-highlight';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const ResetHighlight: Story = {
decorators: [
(storyFn) => {
const emit = useChannel({});
emit(RESET_HIGHLIGHT); //👈 Remove previously highlighted elements
emit(HIGHLIGHT, {
elements: ['header', 'section', 'footer'],
});
return storyFn();
},
],
};
自訂樣式
此擴充套件將標準樣式應用於您為故事啟用的高亮顯示元素。但是,您可以通過擴展有效負載對象並提供 color
和/或 style
屬性來啟用您的自訂樣式。例如
// MyComponent.stories.ts
import type { Meta, StoryObj } from '@storybook/react';
import { useChannel } from '@storybook/preview-api';
import { HIGHLIGHT } from '@storybook/addon-highlight';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const StyledHighlight: Story = {
decorators: [
(storyFn) => {
const emit = useChannel({});
emit(HIGHLIGHT, {
elements: ['.title', '.subtitle'],
color: 'red',
style: 'solid', // 'dotted' | 'dashed' | 'solid' | 'double'
});
return storyFn();
},
],
};