Javascript / convert CSS style string into JS object

后端 未结 10 1045
粉色の甜心
粉色の甜心 2021-01-04 08:41

We\'d like to convert a CSS style entered as string into a JS object.

E.g.,

 var input = \" border:solid 1px; color:red \";

expec

10条回答
  •  庸人自扰
    2021-01-04 09:17

    If you want a tagged template literal syntax that works easily with React, you could do

    const camelCase = str => str.replace(/-(.)/g, (_,p) => p.toUpperCase())
    
    const css2obj = (strings, ...vals) => {
      const css = strings.reduce((acc, str, i) => acc + str + (vals[i] || ''), '')
      const r = /(?<=^|;)\s*([^:]+)\s*:\s*([^;]+)\s*/g, o = {}
      css.replace(r, (m,p,v) => o[camelCase(p)] = v)
      return o
    }
    
    const center = 'center'
    
    const reactInlineCSS = css2obj`
      align-items: ${center};
      justify-content: ${center};
    `
    
    console.log(reactInlineCSS)

提交回复
热议问题