看到一篇文章: https://nbsaw.surge.sh/#/post/71
作者想把
var colors = {
gray: {
default: "#DDDDDD",
light: "#EEEEEE",
dark: "#CCCCCC"
})
}
省去 default, 实现这样的效果:
const Components = styled.div`
background: ${ colors.gray }; // background: #DDDDDD
`
const Components2 = styled.div`
background: ${ colors.gray.light }; // background: #EEEEEE
`
const Components3 = styled.div`
background: ${ colors.gray.dark }; // background: #CCCCCC
`
实现的方法是这样:
const colors = {
gray: Object.assign("#DDDDDD", {
light: "#EEEEEE",
dark: "#CCCCCC"
})
}
一开始是感兴趣的,但是发现自己确实实现不了,返回的 colors.gray 是个 object, 查了下 MDN 上 Object.assign 的首个参数只能是 object, 就算不是 object 也会转成 object。
所以问题是:
- 1、我实现的方式是不是不对?( runtime 和标准的问题?)
- 2、假设这种实现不行,若是想达到这种效果,靠原生怎么实现?(不自己定义函数)