TypeScript 支持 #
基本类型 #
组件 Props 类型 #
tsx
import { ButtonProps, BoxProps, TextProps } from '@chakra-ui/react'
interface CustomCardProps extends BoxProps {
title: string
description?: string
}
function CustomCard({ title, description, ...props }: CustomCardProps) {
return (
<Box p={4} bg="white" shadow="md" {...props}>
<Text fontWeight="bold">{title}</Text>
{description && <Text color="gray.500">{description}</Text>}
</Box>
)
}
主题类型扩展 #
扩展颜色类型 #
tsx
import '@chakra-ui/react'
declare module '@chakra-ui/react' {
interface ThemeCustomization {
colors: {
brand: {
50: string
100: string
200: string
300: string
400: string
500: string
600: string
700: string
800: string
900: string
}
}
}
}
扩展组件 Props #
tsx
import '@chakra-ui/react'
declare module '@chakra-ui/react' {
interface ButtonProps {
variant?: 'primary' | 'secondary' | 'ghost'
}
}
自定义组件类型 #
tsx
import { Box, BoxProps } from '@chakra-ui/react'
import { ReactNode } from 'react'
interface CardProps extends BoxProps {
children: ReactNode
variant?: 'elevated' | 'outline'
}
export function Card({
children,
variant = 'elevated',
...props
}: CardProps) {
const variantStyles = {
elevated: {
shadow: 'md',
bg: 'white',
},
outline: {
borderWidth: '1px',
borderColor: 'gray.200',
bg: 'transparent',
},
}
return (
<Box p={4} borderRadius="lg" {...variantStyles[variant]} {...props}>
{children}
</Box>
)
}
类型安全的主题 #
tsx
import { extendTheme, Theme } from '@chakra-ui/react'
const theme: Partial<Theme> = {
colors: {
brand: {
500: '#2196f3',
},
},
}
export default extendTheme(theme)
类型安全的 Style Props #
tsx
import { SystemStyleObject } from '@chakra-ui/react'
const styles: SystemStyleObject = {
bg: 'blue.500',
color: 'white',
p: 4,
borderRadius: 'md',
}
function StyledBox() {
return <Box sx={styles}>内容</Box>
}
泛型组件 #
tsx
import { ListProps } from '@chakra-ui/react'
interface ItemListProps<T> extends Omit<ListProps, 'children'> {
items: T[]
renderItem: (item: T) => ReactNode
}
function ItemList<T>({ items, renderItem, ...props }: ItemListProps<T>) {
return (
<List {...props}>
{items.map((item, index) => (
<ListItem key={index}>{renderItem(item)}</ListItem>
))}
</List>
)
}
下一步 #
现在你已经掌握了 TypeScript 支持,接下来学习 无障碍指南,了解如何构建无障碍应用!
最后更新:2026-03-28