在为React组件创建主题时,我想知道定义对象类型的最佳方法是什么。基本上,我有一个react组件,它接受一个样式对象来创建主题。如下面:
const datePickerTheme = {
palette: {
primary: "#f5f5f5",
secondary: "#2b4450",
tertiary: "#871111"
},
spacing: ["0px", "4px", "8px", "16px", "32px", "64px"],
};
它将被传递到datepicker组件中,如下所示:
<DatePicker theme={datePickerTheme}/>
在类型脚本上,它具有如下所示的接口:
interface ITheme {
palette: {
primary: string,
secondary?: string,
tertiary?: string,
},
spacing: [],
}
但是,我希望为将来的主题自定义打开界面,以实现其他可能性。基本上,一个人应该能够传递任何种类的主题,但是需要许多键。有没有一种方法可以定义接口,以便在不使用类型“ theme:any”的情况下灵活开放。
这是你想要的吗?您可以在palette
对象中添加任何键。
interface ITheme {
palette: {
primary: string,
secondary: string,
tertiary: string,
[key: string]: string
},
spacing: [],
}
或者,您可以通过提供来限制key的值type
。
type PaletteKey = 'third' | 'fourth';
interface ITheme {
palette: {
primary: string,
secondary: string,
tertiary: string,
[key: PaletteKey]: string
},
spacing: [],
}
对于将来基于的自定义ITheme
,您可以扩展界面。
例如:
interface IPalette {
primary: string;
secondary: string;
tertiary: string;
}
interface ITheme {
palette: IPalette;
spacing: [];
}
type Breakpoints = {
xs: number;
sm: number;
md: number;
lg: number;
xl: number;
};
interface CustomTheme extends ITheme {
palette: IPalette & {
error: string;
success: string;
};
breakpoints: Breakpoints;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句