const createCss = (reset, props) => {
const firsts = Array.from(reset[0])
const variables = reset.slice(1)
let cssText = ''
while(firsts.length > 0 || variables.length > 0){
cssText += firsts.shift()
const v = variables.shift()
if(v !== undefined){
if(typeof v === 'function'){
cssText += v(props)
}else{
cssText += v
}
}
}
return cssText
}
const styled = (...reset) => {
return (props = {}) => {
const div = document.createElement('div')
const cssText = createCss(reset, props)
div.style.cssText = cssText
return div
}
}
const n = 200;
const divDom = styled`
width: ${n}px;
height: ${(props) => props.h}px;
`
console.log(divDom({h: 200}))
如果把真实dom
节点换成react
组件,则是同样的道理! 上述代码可以在浏览器环境中直接运行!