国际化 #

配置语言 #

设置默认语言 #

jsx
import { ChakraProvider, extendTheme } from '@chakra-ui/react'

const theme = extendTheme({
  direction: 'ltr',
  locale: 'zh-CN',
})

function App() {
  return (
    <ChakraProvider theme={theme}>
      <App />
    </ChakraProvider>
  )
}

RTL 支持 #

启用 RTL #

jsx
const theme = extendTheme({
  direction: 'rtl',
})

function App() {
  return (
    <ChakraProvider theme={theme}>
      <Box dir="rtl">
        RTL 内容
      </Box>
    </ChakraProvider>
  )
}

动态切换方向 #

jsx
import { useColorMode, useTheme } from '@chakra-ui/react'

function DirectionToggle() {
  const { direction, toggleDirection } = useTheme()

  return (
    <Button onClick={toggleDirection}>
      当前方向: {direction}
    </Button>
  )
}

组件翻译 #

翻译组件文本 #

jsx
const theme = extendTheme({
  components: {
    Button: {
      defaultProps: {
        loadingText: '加载中...',
      },
    },
    Input: {
      defaultProps: {
        placeholder: '请输入...',
      },
    },
  },
})

日期本地化 #

jsx
import { formatDate } from '@chakra-ui/utils'

function DateDisplay({ date }) {
  const formatted = formatDate(date, { locale: 'zh-CN' })
  
  return <Text>{formatted}</Text>
}

实用示例 #

语言切换 #

jsx
import { useState } from 'react'

const translations = {
  'zh-CN': {
    welcome: '欢迎',
    login: '登录',
    logout: '退出',
  },
  'en-US': {
    welcome: 'Welcome',
    login: 'Login',
    logout: 'Logout',
  },
}

function LanguageSwitcher() {
  const [locale, setLocale] = useState('zh-CN')
  const t = translations[locale]

  return (
    <Box>
      <HStack mb={4}>
        <Button size="sm" onClick={() => setLocale('zh-CN')}>
          中文
        </Button>
        <Button size="sm" onClick={() => setLocale('en-US')}>
          English
        </Button>
      </HStack>
      <Text>{t.welcome}</Text>
      <Button>{t.login}</Button>
    </Box>
  )
}

下一步 #

现在你已经掌握了国际化,接下来学习 项目结构,了解如何组织 Chakra UI 项目代码!

最后更新:2026-03-28