主题定制 #
主题概述 #
Chakra UI 使用主题对象来定义设计系统的各个方面,包括颜色、排版、间距等。你可以通过 extendTheme 函数扩展默认主题。
jsx
import { ChakraProvider, extendTheme } from '@chakra-ui/react'
const theme = extendTheme({
colors: {
brand: {
500: '#2196f3',
},
},
})
function App() {
return (
<ChakraProvider theme={theme}>
<App />
</ChakraProvider>
)
}
自定义颜色 #
添加品牌颜色 #
jsx
const theme = extendTheme({
colors: {
brand: {
50: '#e3f2fd',
100: '#bbdefb',
200: '#90caf9',
300: '#64b5f6',
400: '#42a5f5',
500: '#2196f3',
600: '#1e88e5',
700: '#1976d2',
800: '#1565c0',
900: '#0d47a1',
},
},
})
覆盖默认颜色 #
jsx
const theme = extendTheme({
colors: {
blue: {
500: '#2196f3',
},
},
})
自定义字体 #
jsx
const theme = extendTheme({
fonts: {
heading: `'Noto Sans SC', sans-serif`,
body: `'Noto Sans SC', sans-serif`,
mono: `'Fira Code', monospace`,
},
fontSizes: {
xs: '0.75rem',
sm: '0.875rem',
md: '1rem',
lg: '1.125rem',
xl: '1.25rem',
'2xl': '1.5rem',
'3xl': '1.875rem',
'4xl': '2.25rem',
},
})
自定义组件样式 #
全局组件样式 #
jsx
const theme = extendTheme({
components: {
Button: {
baseStyle: {
fontWeight: 'medium',
borderRadius: 'md',
},
variants: {
custom: {
bg: 'brand.500',
color: 'white',
_hover: {
bg: 'brand.600',
},
},
},
defaultProps: {
colorScheme: 'brand',
},
},
},
})
自定义组件变体 #
jsx
const theme = extendTheme({
components: {
Button: {
variants: {
outline: {
border: '2px solid',
borderColor: 'currentColor',
bg: 'transparent',
},
solid: {
bg: 'currentColor',
color: 'white',
},
},
},
},
})
自定义间距 #
jsx
const theme = extendTheme({
space: {
0: '0',
1: '0.25rem',
2: '0.5rem',
3: '0.75rem',
4: '1rem',
5: '1.25rem',
6: '1.5rem',
8: '2rem',
10: '2.5rem',
12: '3rem',
16: '4rem',
20: '5rem',
24: '6rem',
},
})
自定义断点 #
jsx
const theme = extendTheme({
breakpoints: {
sm: '480px',
md: '768px',
lg: '992px',
xl: '1280px',
'2xl': '1536px',
},
})
全局样式 #
jsx
const theme = extendTheme({
styles: {
global: {
body: {
bg: 'gray.50',
color: 'gray.800',
},
'h1, h2, h3, h4, h5, h6': {
fontWeight: 'bold',
},
a: {
color: 'blue.500',
_hover: {
textDecoration: 'underline',
},
},
},
},
})
主题配置结构 #
jsx
const theme = extendTheme({
colors: {},
fonts: {},
fontSizes: {},
fontWeights: {},
lineHeights: {},
letterSpacings: {},
space: {},
sizes: {},
borders: {},
borderWidths: {},
radii: {},
shadows: {},
breakpoints: {},
zIndices: {},
styles: {
global: {},
},
components: {},
})
实用示例 #
完整主题配置 #
jsx
const theme = extendTheme({
colors: {
brand: {
50: '#e3f2fd',
100: '#bbdefb',
200: '#90caf9',
300: '#64b5f6',
400: '#42a5f5',
500: '#2196f3',
600: '#1e88e5',
700: '#1976d2',
800: '#1565c0',
900: '#0d47a1',
},
},
fonts: {
heading: `'Noto Sans SC', sans-serif`,
body: `'Noto Sans SC', sans-serif`,
},
styles: {
global: {
body: {
bg: 'gray.50',
},
},
},
components: {
Button: {
defaultProps: {
colorScheme: 'brand',
},
},
Input: {
defaultProps: {
focusBorderColor: 'brand.500',
},
},
},
})
下一步 #
现在你已经掌握了主题定制,接下来学习 颜色模式,了解如何实现深色/浅色模式切换!
最后更新:2026-03-28