Typescript在自定义CSS样式中的使用

文章介绍了如何利用TypeScript的keyof和Record等类型工具,来限制自定义CSS样式对象的结构,确保每个rule的key属于预定义的styleName数组,并且value是CSSStyleDeclaration的Partial类型,以此增强代码的类型安全性和可维护性。
摘要由CSDN通过智能技术生成


前言


一、使用情景

  • 以对象的形式书写CSS样式
  • 限制一个style sheet中rule数量以及名称
  • Partial以及Record使用

二、开始编辑

1.创建css的rule的内容范围

// <const>只读的
const styleName = <const>['form', 'lang', 'action', 'input', 'center'];

2.创建每个style sheet的校验

2.1

  • 限定每个rull中的key的范围,即以styleName的内容作为对象的key
  • Keys:styleName[0]则表示’form’
//限定每个rull中的key的范围,即以styleName的内容作为对象的key
//Keys:styleName[0]则表示'form'
export type Keys = typeof styleName[number];

2.2

  • Record表示拥有多个格式相同类似的内容,Partial表示为可选的。
  • Record<Keys,Partial> 表示Istyle的内容格式为:
  • 以styleName中的某一项为key,CSSStyleDeclaration为value组成的序列对象
//Record表示拥有多个格式相同类似的内容,Partial表示为可选的。
//Record<Keys,Partial<CSSStyleDeclaration>> 表示Istyle的内容格式为:
//以styleName中的某一项为key,CSSStyleDeclaration为value组成的序列对象
export type Istyle = Partial<Record<Keys, Partial<CSSStyleDeclaration>>>;

2.3

//示例
export const logo = {
  form: {
    width: '25%',
    minWidth: '200px',
    maxWidth: '400px',
    margin: 'auto',
  },
  lang: { textAlign: 'right' },
  action: {
    textAlign: 'center',
    marginTop: '60px',
  },
  input: {
    borderRadius: '4px',
    border: '1px solid black',
  },
};

三、完整数据

// export enum StyleName { form = "form", lang = "lang", action = "action", input = "input", }
const styleName = <const>['form', 'lang', 'action', 'input', 'center'];
export type Keys = typeof styleName[number];
export type Istyle = Partial<Record<Keys, Partial<CSSStyleDeclaration>>>;

export const logo = {
  form: {
    width: '25%',
    minWidth: '200px',
    maxWidth: '400px',
    margin: 'auto',
  },
  lang: { textAlign: 'right' },
  action: {
    textAlign: 'center',
    marginTop: '60px',
  },
  input: {
    borderRadius: '4px',
    border: '1px solid black',
  },
};
export const lt: Istyle = {
  form: {
    width: '25%',
    minWidth: '200px',
    maxWidth: '400px',
    margin: 'auto',
    marginTop: '-20px',
  },
  lang: { textAlign: 'right' },
  action: {
    textAlign: 'center',
  },
  input: {
    borderRadius: '4px',
    border: '1px solid #0084c0',
  },
};
export const nologo: Istyle = {
  form: {
    width: '25%',
    minWidth: '200px',
    maxWidth: '400px',
    margin: 'auto',
  },
  lang: { textAlign: 'right' },
  action: {
    textAlign: 'center',
  },
  input: {
    borderRadius: '4px',
    border: '1px solid black',
  },
};

export const allStyle = { logo, lt, nologo };



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值