无障碍指南 #
无障碍概述 #
Chakra UI 遵循 WAI-ARIA 规范,所有组件默认具有无障碍特性。
基本原则 #
1. 语义化 HTML #
tsx
<Box as="nav">
<List as="ul">
<ListItem as="li">
<Link href="/">首页</Link>
</ListItem>
</List>
</Box>
2. 键盘导航 #
tsx
<Button
onClick={handleClick}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
handleClick()
}
}}
>
按钮
</Button>
3. 焦点管理 #
tsx
import { useRef, useEffect } from 'react'
function Modal({ isOpen, onClose }) {
const initialRef = useRef()
return (
<Modal isOpen={isOpen} onClose={onClose} initialFocusRef={initialRef}>
<ModalOverlay />
<ModalContent>
<Input ref={initialRef} />
</ModalContent>
</Modal>
)
}
ARIA 属性 #
aria-label #
tsx
<IconButton
aria-label="搜索"
icon={<SearchIcon />}
/>
<Button aria-label="关闭对话框">
<CloseIcon />
</Button>
aria-describedby #
tsx
<FormControl>
<FormLabel>密码</FormLabel>
<Input
type="password"
aria-describedby="password-hint"
/>
<FormHelperText id="password-hint">
密码至少 8 位,包含字母和数字
</FormHelperText>
</FormControl>
aria-live #
tsx
<Box aria-live="polite" aria-atomic="true">
{notification}
</Box>
图片无障碍 #
tsx
<Image
src="photo.jpg"
alt="用户头像"
/>
<Image
src="decorative.jpg"
alt=""
role="presentation"
/>
表单无障碍 #
tsx
<FormControl isRequired>
<FormLabel>用户名</FormLabel>
<Input
aria-required="true"
aria-invalid={errors.username ? 'true' : 'false'}
/>
<FormErrorMessage>{errors.username}</FormErrorMessage>
</FormControl>
按钮无障碍 #
tsx
<Button
aria-busy={isLoading}
aria-disabled={isDisabled}
disabled={isDisabled}
>
{isLoading ? '加载中...' : '提交'}
</Button>
链接无障碍 #
tsx
<Link
href="/about"
aria-current={isActive ? 'page' : undefined}
>
关于我们
</Link>
跳过链接 #
tsx
<Link
href="#main-content"
position="absolute"
top="-40px"
left={0}
_focus={{
top: 0,
bg: 'blue.500',
color: 'white',
p: 4,
zIndex: 'tooltip',
}}
>
跳到主要内容
</Link>
<Box id="main-content" as="main">
主要内容
</Box>
颜色对比度 #
确保文字和背景颜色对比度符合 WCAG 标准:
tsx
<Text color="gray.800" bg="white">
高对比度文字
</Text>
屏幕阅读器测试 #
使用屏幕阅读器测试你的应用:
- macOS: VoiceOver
- Windows: NVDA, JAWS
- iOS: VoiceOver
- Android: TalkBack
无障碍检查清单 #
- [ ] 所有图片有 alt 属性
- [ ] 表单字段有关联的标签
- [ ] 按钮有可访问的名称
- [ ] 链接有描述性文本
- [ ] 颜色对比度足够
- [ ] 键盘可以导航
- [ ] 焦点状态可见
- [ ] 错误消息可访问
恭喜完成! #
你已经完成了 Chakra UI 完全指南的学习!现在你已经掌握了从基础到高级的所有 Chakra UI 技能,可以开始构建出色的 React 应用了!
最后更新:2026-03-28