反白
Storybook 的 Highlight 附加元件是一個有用的工具,可讓您在視覺上偵錯元件,當作為獨立附加元件使用時,可讓您反白顯示 Story 中的特定 DOM 節點,或增強其他附加元件 (例如 Accessibility 附加元件) 以通知您元件內的可存取性問題。
反白 DOM 元素
若要使用附加元件反白顯示 DOM 元素,您需要從 Story 或附加元件內發出 HIGHLIGHT
事件。事件酬載必須包含一個 elements
屬性,此屬性已指派給一個選取器陣列,以符合您要反白顯示的元素。例如
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: ['h2', 'a', '.storybook-button'],
});
return storyFn();
},
],
};
我們建議選擇最明確的選取器,以避免反白顯示其他附加元件使用的元素。這是因為附加元件會嘗試將選取器與整個 DOM 樹狀結構進行比對。
重設反白顯示的元素
Storybook 會在 Story 之間轉換時自動移除反白顯示的元素。但是,如果您需要手動清除它們,您可以從 Story 或附加元件內發出 RESET_HIGHLIGHT
事件。例如
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();
},
],
};
從 useChannel
API hook 衍生而來的 emit
函式會在 Storybook 的 UI 中建立一個通訊通道,以偵聽事件並相應更新 UI。Highlight 附加元件會使用此通道來偵聽自訂事件,並相應更新反白顯示的元素 (如果有的話)。
自訂樣式
依預設,附加元件會對您為 Story 啟用的反白顯示元素套用標準樣式。但是,您可以擴充酬載物件,並提供 color
和/或 style
屬性,來啟用您的自訂樣式。例如
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: ['h2', 'a', '.storybook-button'],
color: 'blue',
style: 'double', // 'dotted' | 'dashed' | 'solid' | 'double'
});
return storyFn();
},
],
};
API
參數
此附加元件會在 highlight
命名空間下,將下列參數提供給 Storybook
disable
類型:boolean
停用此附加元件的行為。如果您希望在整個 Storybook 中停用此附加元件,您應該在註冊 addon-essentials
時執行此操作。請參閱基本附加元件的說明文件以取得更多資訊。
此參數在允許在更特定層級進行覆寫時最有用。例如,如果此參數在專案層級設定為 true
,則可以透過在 meta(元件)或 story 層級將其設定為 false
來重新啟用它。
匯出
此附加元件會將以下匯出內容貢獻給 Storybook
import { HIGHLIGHT, RESET_HIGHLIGHT } from '@storybook/addon-highlight';
HIGHLIGHT
類型:string
用於醒目提示 DOM 元素的事件。事件酬載必須包含一個 elements
屬性,該屬性已指派給一個選取器陣列,這些選取器符合您想要醒目提示的元素。請參閱上方的使用範例。
RESET_HIGHLIGHT
類型:string
用於清除所有從醒目提示元素中醒目提示的事件。請參閱上方的使用範例。