项目结构 #

推荐目录结构 #

text
src/
├── components/
│   ├── ui/                    # 基础 UI 组件
│   │   ├── Button/
│   │   │   ├── Button.tsx
│   │   │   ├── Button.test.tsx
│   │   │   └── index.ts
│   │   ├── Input/
│   │   └── ...
│   ├── layout/                # 布局组件
│   │   ├── Header/
│   │   ├── Footer/
│   │   ├── Sidebar/
│   │   └── Layout.tsx
│   └── features/              # 功能组件
│       ├── Auth/
│       ├── Dashboard/
│       └── Settings/
├── theme/
│   ├── index.ts               # 主题入口
│   ├── colors.ts              # 颜色配置
│   ├── fonts.ts               # 字体配置
│   ├── components/            # 组件主题
│   │   ├── Button.ts
│   │   ├── Input.ts
│   │   └── ...
│   └── styles.ts              # 全局样式
├── hooks/                     # 自定义 Hooks
│   ├── useAuth.ts
│   └── useToast.ts
├── utils/                     # 工具函数
├── pages/                     # 页面组件
└── App.tsx

主题文件组织 #

theme/index.ts #

tsx
import { extendTheme } from '@chakra-ui/react'
import colors from './colors'
import fonts from './fonts'
import components from './components'
import styles from './styles'

const config = {
  initialColorMode: 'light',
  useSystemColorMode: true,
}

const theme = extendTheme({
  config,
  colors,
  fonts,
  components,
  styles,
})

export default theme

theme/colors.ts #

tsx
const colors = {
  brand: {
    50: '#e3f2fd',
    100: '#bbdefb',
    200: '#90caf9',
    300: '#64b5f6',
    400: '#42a5f5',
    500: '#2196f3',
    600: '#1e88e5',
    700: '#1976d2',
    800: '#1565c0',
    900: '#0d47a1',
  },
}

export default colors

theme/components/Button.ts #

tsx
const Button = {
  baseStyle: {
    fontWeight: 'medium',
    borderRadius: 'md',
  },
  variants: {
    solid: {
      bg: 'brand.500',
      color: 'white',
      _hover: {
        bg: 'brand.600',
      },
    },
    outline: {
      border: '2px solid',
      borderColor: 'brand.500',
      color: 'brand.500',
    },
  },
  defaultProps: {
    colorScheme: 'brand',
  },
}

export default Button

组件组织 #

组件文件结构 #

text
Button/
├── Button.tsx         # 组件实现
├── Button.test.tsx    # 测试文件
├── Button.stories.tsx # Storybook 故事
├── types.ts           # 类型定义
└── index.ts           # 导出入口

组件示例 #

tsx
import { Button as ChakraButton, ButtonProps } from '@chakra-ui/react'

interface CustomButtonProps extends ButtonProps {
  loadingText?: string
}

export function Button({ 
  loadingText = '加载中...', 
  ...props 
}: CustomButtonProps) {
  return (
    <ChakraButton
      loadingText={loadingText}
      {...props}
    />
  )
}

下一步 #

现在你已经了解了项目结构,接下来学习 性能优化,了解如何优化 Chakra UI 应用性能!

最后更新:2026-03-28