性能优化 #

减少重渲染 #

使用 React.memo #

tsx
import { memo } from 'react'
import { Box } from '@chakra-ui/react'

const Card = memo(function Card({ title, description }) {
  return (
    <Box p={4} bg="white" shadow="md">
      <Text fontWeight="bold">{title}</Text>
      <Text color="gray.500">{description}</Text>
    </Box>
  )
})

使用 useMemo 和 useCallback #

tsx
import { useMemo, useCallback } from 'react'

function UserList({ users }) {
  const sortedUsers = useMemo(() => {
    return [...users].sort((a, b) => a.name.localeCompare(b.name))
  }, [users])

  const handleClick = useCallback((userId) => {
    console.log('User clicked:', userId)
  }, [])

  return (
    <VStack>
      {sortedUsers.map((user) => (
        <UserCard key={user.id} user={user} onClick={handleClick} />
      ))}
    </VStack>
  )
}

按需导入 #

只导入需要的组件 #

tsx
import { Button } from '@chakra-ui/react'
import { SearchIcon } from '@chakra-ui/icons'

优化主题 #

避免过度扩展主题 #

tsx
const theme = extendTheme({
  colors: {
    brand: {
      500: '#2196f3',
    },
  },
})

使用 CSS 变量 #

tsx
const theme = extendTheme({
  cssVarPrefix: 'ck',
})

懒加载组件 #

tsx
import { lazy, Suspense } from 'react'
import { Spinner } from '@chakra-ui/react'

const HeavyComponent = lazy(() => import('./HeavyComponent'))

function App() {
  return (
    <Suspense fallback={<Spinner />}>
      <HeavyComponent />
    </Suspense>
  )
}

虚拟列表 #

对于大型列表,使用虚拟滚动:

tsx
import { FixedSizeList } from 'react-window'

function VirtualList({ items }) {
  const Row = ({ index, style }) => (
    <Box style={style} p={2}>
      <Text>{items[index].name}</Text>
    </Box>
  )

  return (
    <FixedSizeList
      height={400}
      width="100%"
      itemCount={items.length}
      itemSize={50}
    >
      {Row}
    </FixedSizeList>
  )
}

图片优化 #

tsx
<Image
  src="image.jpg"
  alt="描述"
  loading="lazy"
  fallback={<Spinner />}
/>

下一步 #

现在你已经掌握了性能优化,接下来学习 TypeScript 支持,了解如何在 Chakra UI 中使用 TypeScript!

最后更新:2026-03-28