标签模板,css in js 简单实现

52 阅读1分钟

模版字符串的普通用法

当说到模版字符串的时候,第一时间想到的是

const firstName = 'kris'
const lastName = 'jame'
const str = `i'm ${firstName}`

console.log(str) // i'm kris


const flag = true
const str1 = `Is show ${flag ? lastName : firstName}`

console.log(str1) // Is show jame

标签模板

案例: css in js, 如(styled-component, emotion)

使用:

const person = "Mike";
const age = 28;

function myTag(strings, personExp, ageExp) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "
  const str2 = strings[2]; // "."

  const ageStr = ageExp > 99 ? "centenarian" : "youngster";

  // 我们甚至可以返回使用模板字面量构建的字符串
  return `${str0}${personExp}${str1}${ageStr}${str2}`;
}

const output = myTag`That ${person} is a ${age}.`;

console.log(output);
// That Mike is a youngster.

demo(css in js)

使用标签属性创建一个a标签

<script>
  const createTagA = () => {
    const height = 10
    const width = 100
    const url = 'www.baidu.com'
    const title = 'baidu'


    const a = document.createElement('a')
    a.style.height = height + 'px'
    a.style.width = width + 'px'
    a.style.color = 'red'
    a.style.background = 'white'
    a.style.fontSize = '16px'

    a.href = url
    a.title = title
    a.innerHTML = '哈哈哈哈哈哈'


    document.body.appendChild(a)
  }

  createTagA()
</script>

使用标签属性来实现

  1. 在原型上添加styles 和 props 方法
  2. 在标签上添加属性
<script>
  const createTagA = () => {
    const height = '10px'
    const width = '100px'
    const url = 'www.baidu.com'
    const title = 'baidu'
    const innerHTML = '哈哈哈哈哈哈'


    const getAttrValue = (strings, attrs) => {
      const removetrim = (str) => {
        // 去除\n
        str.replace(/[\n\r]/g, '').replace(/^\s+|\s+$/g,'');
        return str.trim()
      }

      const str = strings.reduce((allStr, string, len) => {
        if (len !== strings.length -1) {
          return `${allStr}${string}${attrs[len]}`
        }
        return allStr
      }, '')

      const strs = str.split(';')

      const styleAttr = strs.reduce((val, strsItem, len) => {
        const items= strsItem.split(':')
        const key = removetrim(items[0])
        const value = removetrim(items[1])
        val[key] = value
        return val
      }, {})

      return styleAttr

    }


    HTMLElement.prototype.styles = function(strings, ...attrs) {

      const styleAttr = getAttrValue(strings, attrs)

      for(key in styleAttr) {
        this.style[key] = styleAttr[key]
      }

      return this
    }

    HTMLElement.prototype.props = function(strings, ...attrs) {
      const styleAttr = getAttrValue(strings, attrs)

      for(key in styleAttr) {
        this[key] = styleAttr[key]
      }

      return this
    }

    const a = document.createElement('a')

    a.styles`
      height: ${height};
      color: red;
      background: white;
      fontSize: 16px;
      width: ${width};
    `.props`
      href: ${url};
      title: ${title};
      innerHTML: ${innerHTML};
    `

    document.body.appendChild(a)
  }

  createTagA()
</script>