安装
npm i storybook-mock-date-decorator
API
将装饰器添加到 Storybook 后,您可以在故事中使用参数名称 date
配置日期。
用法
此处的语法对每个 Storybook 版本均有效。如果您使用的是不同版本,或者自上次更新以来发布了新版本,则可能需要查看官方文档。
Storybook 8
import { mockDateDecorator } from "storybook-mock-date-decorator";
/** @type { import('@storybook/react').Preview } */
const preview = {
decorators: [mockDateDecorator],
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
},
},
},
};
export default preview;
// stories/Button.stories.js
export default {
title: 'Example/Button',
component: Button,
parameters: {
date: new Date(1999, 10, 24),
},
};
export const Primary = {
args: {
primary: true,
label: 'Button',
},
parameters: {
date: new Date(2021, 1, 1),
}
};
Storybook 7
// .storybook/preview.js
import { mockDateDecorator } from "storybook-mock-date-decorator/legacy";
export let decorators = [mockDateDecorator];
Storybook 6
// .storybook/preview.js
import { addDecorator } from "@storybook/react";
import { mockDateDecorator } from "storybook-mock-date-decorator/legacy";
addDecorator(mockDateDecorator);
然后在您的 Storybook 中,您可以使用以下代码为组件的所有故事模拟/冻结日期
import { Meta } from "@storybook/react"
import { YourComponent } from "./your-component"
export default {
title: "YourComponent",
component: YourComponent,
parameters: {
date: new Date("March 10, 2021 10:00:00"),
},
} as Meta
或者,您可以为特定故事模拟/冻结日期
import { Meta } from "@storybook/react"
import { YourComponent } from "./your-component"
export default {
title: "YourComponent",
component: YourComponent,
} as Meta
export function Default() {
return <div>hello world at {new Date().toLocaleString()}</div>
}
export function WithMockedDate() {
return <div>hello world! with mocked date of March 10th at {new Date().toLocaleString()}</div>
}
WithMockedDate.parameters = {
date: new Date("March 10, 2021 10:00:00"),
}