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


前言


一、使用情景

  • 以对象的形式书写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 };



猜你喜欢

转载自blog.csdn.net/CherishTaoTao/article/details/129498218