如何在React-JSS的JSS主题内部引用主题自身定义的值?
我在使用react-jss时,想在主题里定义
defaultBorder并引用同一主题内的baseColor,尝试了下面的写法但行不通:const theme = { baseColor: '#aaaaaa', defaultBorder: [[1, 'solid', this.baseColor]] }想问这个需求是不是无法实现?是不是必须像下面这样,先在外部定义颜色再分别引用?
const baseColor = '#aaaaaa'; const theme = { baseColor: baseColor, defaultBorder: [[1, 'solid', baseColor]] }
Hey there! Great question—you absolutely don't have to rely on an external variable for this, though that approach does work perfectly fine. Let's break down why your first attempt failed, and what other options you have:
First off, the this.baseColor didn't work because when you're creating an object literal like that, this doesn't point to the theme object you're building. It actually refers to the surrounding context (like window in non-strict mode, or undefined in strict mode), so it can't access the baseColor property you just defined.
Here are two alternative approaches that let you reference baseColor directly within the theme:
1. Use a getter property
You can turn defaultBorder into a getter function. Getters run when the property is accessed, not when the object is created—so at that point, this will correctly point to the theme object:
const theme = { baseColor: '#aaaaaa', get defaultBorder() { return [1, 'solid', this.baseColor]; } };
Just keep in mind that this returns a new array every time you access theme.defaultBorder. For most React-JSS use cases, this isn't a problem at all.
2. Build the theme in two steps
First define the core properties, then add the dependent one afterward. This way you can directly reference the already-defined baseColor:
const theme = { baseColor: '#aaaaaa' }; theme.defaultBorder = [1, 'solid', theme.baseColor];
And of course, your original external variable approach is totally valid too—especially if you need to reuse that baseColor value outside the theme object itself. All these methods work, so pick the one that feels clearest for your codebase!
内容的提问来源于stack exchange,提问作者Vegar

