如何在Storybook中为Luxon DateTime对象配置友好日期控件?
为Storybook配置Luxon DateTime对象的友好日期控件
完全可以实现,核心是通过Storybook的argTypes配置,在日期选择器的字符串值和Luxon DateTime对象之间做双向转换,具体方案如下:
1. 基础配置:用argTypes实现转换
在你的组件Story文件中,针对接收Luxon DateTime的输入参数,配置argTypes:
- 指定控件类型为
date,启用可视化日期选择器 - 用
transform函数把控件传入的日期字符串转成Luxon DateTime对象 - 把组件默认的Luxon值转成ISO字符串,适配控件的输入格式
示例代码:
import { Meta, StoryObj } from '@storybook/angular'; import { YourComponent } from './your.component'; import { DateTime } from 'luxon'; const meta: Meta<YourComponent> = { component: YourComponent, argTypes: { // 假设组件输入名为selectedDate,类型是Luxon DateTime selectedDate: { control: { type: 'date' }, // 控件字符串转Luxon对象 transform: (dateStr: string) => dateStr ? DateTime.fromISO(dateStr) : null, // 默认值转成控件能识别的ISO日期字符串 defaultValue: DateTime.now().toISODate(), }, }, }; export default meta; type Story = StoryObj<YourComponent>; export const Default: Story = { args: { selectedDate: DateTime.now(), }, };
2. 同步组件内部变更到控件(可选)
如果组件内部会修改日期并通过输出事件通知(比如selectedDateChange),可以在Story的play函数里监听事件,把更新后的Luxon对象转成字符串同步回控件:
export const WithSync: Story = { args: { selectedDate: DateTime.now(), }, play: async ({ canvasElement, args }) => { const component = canvasElement.querySelector('app-your-component') as YourComponent; component.selectedDateChange.subscribe((updatedDate: DateTime) => { args.selectedDate = updatedDate.toISODate(); }); }, };
3. 封装复用(可选)
如果多个组件都需要处理Luxon日期,可以封装一个通用配置函数,减少重复代码:
import { DateTime } from 'luxon'; // 通用Luxon日期argType配置函数 export const getLuxonDateArgType = (defaultDate?: DateTime) => ({ control: { type: 'date' }, transform: (dateStr: string) => dateStr ? DateTime.fromISO(dateStr) : null, defaultValue: defaultDate?.toISODate() ?? DateTime.now().toISODate(), }); // 在Story中调用 argTypes: { selectedDate: getLuxonDateArgType(DateTime.fromISO('2024-05-20')), }
这样配置后,你就能用Storybook的日期选择器直观编辑组件的Luxon DateTime输入,同时保证类型匹配。
内容的提问来源于stack exchange,提问作者Peter T.
相关产品推荐
相关产品推荐

