storybook-fixtures
透過使用本地資料(JSON 檔案或硬編碼)甚至是 URL 來獲取資料,將資料夾加入您的元件。
安裝
npm install -D storybook-fixtures
在 .storybook/main.js
的擴充套件列表中加入 storybook-fixtures
module.exports = {
addons: ['storybook-fixtures'],
};
將會出現一個新的「Fixtures」面板,其中包含作為子標籤的固定裝置區塊。固定裝置區塊包含固定裝置變體,可以透過點擊或鍵盤快捷鍵切換 - 鍵盤 1
到 9
對應前 9 個變體。
變體也可以使用 Vim 風格的導航鍵依序切換:j
和 k
可以向上和向下移動變體列表。
區塊標籤可以使用 h
和 l
來分別切換到左側和右側標籤。
用法
固定裝置定義必須包含固定裝置區塊名稱作為鍵,並將變體作為其屬性。
import { withFixtures } from 'storybook-fixtures';
import pantheraData from '../__fixtures__/panthera.json';
// Global fixtures available in all stories for a given module
export default {
title: 'storybook-fixtures',
decorators: [
withFixtures({
// override the default setting and show single fixture tab
__singleTab: true,
// fixture sections
collection: pantheraData,
}),
],
};
// Currently selected fixture is injected in story context
export const myLocalFixture = ({ fixture }) => {
return <MyComponent data={fixture} />;
};
// Fixtures that have strings as values are assumed remote URL and will be fetched
// when the story is selected.
export const myRemoteFixture = ({ fixture }) => {
return <MyComponent data={fixture} />;
};
// Fixtures can be added per story via story parameters
myRemoteFixture.parameters = {
fixtures: {
// fixture sections (key is a tab label for multiple variant sets)
variantTypes: {
// variants (key is label)
'Text fixture': 'Lorem ipsum',
'Array fixture': ['One', 'Two'],
'Object fixture': {
title: 'Tiger',
description: 'Largest species of the cat family',
},
'My remote fixture': 'https://example.com/data.json',
},
},
};
變體可以分組為集合並獨立控制。當只定義一個集合時,集合標籤會隱藏。
所有選擇都儲存在本機儲存空間中,並且任何固定裝置選擇都可以在新的獨立標籤中開啟(沒有 Storybook UI)。選擇會編碼在查詢字串中。
每個變體值都可以是 URL,在這種情況下,將會提取該 URL,並將結果作為其值傳回。
在 Storybook v6 中,此附加元件會自動將固定裝置裝飾器全域包含。只需將 storybook-fixtures
新增到 main.js
中的 addons
陣列,任何故事都可以使用 parameters
靜態屬性接收固定裝置物件(請參閱上文)。
固定裝置設定
withFixtures
裝飾器有以雙底線為字首的特殊屬性。這些屬性可以變更固定裝置的顯示方式的特定行為。
__singleTab
(預設為false
)- 固定裝置會分組為多個標籤。固定裝置物件中的每個鍵都會對應到一個標籤。當固定裝置物件中只有一個屬性時,預設不會顯示單一標籤。
匯入
withFixtures
與 Storybook Fixtures 面板通訊並顯示所選固定裝置變體的固定裝置裝飾器。
keyBy
Lodash 公用程式的匯出,將集合(物件陣列)轉換為物件,以依選擇的鍵分組。