跳至主要内容

创建主题

注意

需要在 StyleX Babel 配置中启用 unstable_moduleResolution 选项才能启用主题 API。

定义变量后,可以创建备选“主题”以覆盖特定 UI 子树中这些变量的值。

创建主题

任何变量组都可以像这样导入以创建主题

themes.js
import * as stylex from '@stylexjs/stylex';
import {colors, spacing} from './tokens.stylex';

// A constant can be used to avoid repeating the media query
const DARK = '@media (prefers-color-scheme: dark)';

// Dracula theme
export const dracula = stylex.createTheme(colors, {
primaryText: {default: 'purple', [DARK]: 'lightpurple'},
secondaryText: {default: 'pink', [DARK]: 'hotpink'},
accent: 'red',
background: {default: '#555', [DARK]: 'black'},
lineColor: 'red',
});

应用主题

“主题”是一个类似于使用 stylex.create() 创建的样式对象。可以使用 stylex.props() 将其应用于元素,以覆盖该元素及其所有后代的变量。

components/MyComponent.js
import * as stylex from '@stylexjs/stylex';
import {colors, spacing} from '../tokens.styles';
import {dracula} from '../themes';

const styles = stylex.create({
container: {
color: colors.primaryText,
backgroundColor: colors.background,
padding: spacing.medium,
},
});

<div {...stylex.props(dracula, styles.container)}>{children}</div>;

注意:创建主题时,必须覆盖变量组中的所有变量。此选择是为了帮助捕获意外遗漏。即使是以偶尔的乏味为代价。

与定义和使用变量不同,主题可以在代码库中的任何位置使用 stylex.createTheme() 创建,并在文件或组件之间传递。

信息

如果对同一 HTML 元素应用了同一变量组的多个主题,则最后一个应用的主题优先。