本技能提供 Tamagui v1.x 超基础的模式,重点涵盖 Config v4、编译器优化、复合组件及常见错误。
必读上下文加载
使用以下组件时,请在编写代码前阅读对应的模式文件:
| 组件类型 | 必读文件 | 跨技能 |
|---|---|---|
| Dialog、Sheet、模态覆盖层 | @DIALOG_PATTERNS.md | |
| Form、Input、Label、验证 | @FORM_PATTERNS.md | typescript-best-practices (zod) |
| 动画、过渡 | @ANIMATION_PATTERNS.md | |
| Popover、Tooltip、Select | @OVERLAY_PATTERNS.md | |
| 编译器优化 | @COMPILER_PATTERNS.md | |
| 设计令牌、主题 | @DESIGN_SYSTEM.md |
Config v4 快速开始
使用 @tamagui/config/v4 进行简化设置:
// tamagui.config.ts
import { defaultConfig } from '@tamagui/config/v4'
import { createTamagui } from 'tamagui'
export const config = createTamagui(defaultConfig)
type CustomConfig = typeof config
declare module 'tamagui' {
interface TamaguiCustomConfig extends CustomConfig {}
}
推荐设置(将 flexBasis 对齐 React Native):
export const config = createTamagui({
...defaultConfig,
settings: {
...defaultConfig.settings,
styleCompat: 'react-native',
},
})
createThemes 模式
对于自定义主题,使用 createThemes 配合 palette/accent/childrenThemes:
import { createThemes, defaultComponentThemes } from '@tamagui/config/v4'
const generatedThemes = createThemes({
componentThemes: defaultComponentThemes,
base: {
palette: {
dark: ['#050505', '#151515', /* ...12种颜色 */ '#fff'],
light: ['#fff', '#f8f8f8', /* ...12种颜色 */ '#000'],
},
extra: {
light: { ...Colors.blue, shadowColor: 'rgba(0,0,0,0.04)' },
dark: { ...Colors.blueDark, shadowColor: 'rgba(0,0,0,0.2)' },
},
},
accent: {
palette: { dark: lightPalette, light: darkPalette }, // 反转
},
childrenThemes: {
blue: { palette: { dark: Object.values(Colors.blueDark), light: Object.values(Colors.blue) } },
red: { /* ... */ },
green: { /* ... */ },
},
})
令牌和主题语法
$ 前缀规则
- Props:使用
$前缀进行令牌引用:<Text color="$color" fontSize="$4" /> - 主题键:在主题定义中没有
$:{ color: palette[11] } - 变体中的令牌访问:使用
tokens.size[name]模式
变体展开运算符
特殊的展开运算符将令牌类别映射到变体值:
const Button = styled(View, {
variants: {
size: {
// 映射 size 令牌:$1, $2, $true, 等
'...size': (size, { tokens }) => ({
height: tokens.size[size] ?? size,
borderRadius: tokens.radius[size] ?? size,
gap: tokens.space[size]?.val * 0.2,
}),
},
textSize: {
// 映射 fontSize 令牌
'...fontSize': (name, { font }) => ({
fontSize: font?.size[name],
}),
},
} as const,
})
重要:在 variants 对象上使用 as const,直到 TypeScript 支持推断的 const 泛型。
使用 createStyledContext 实现复合组件
对于类似 <Button><Button.Text>Click</Button.Text></Button> 的复合 API:
import {
SizeTokens,
View,
Text,
createStyledContext,
styled,
withStaticProperties,
} from '@tamagui/core'
// 1. 创建带有共享变体类型的上下文
export const ButtonContext = createStyledContext<{ size: SizeTokens }>({
size: '$medium',
})
// 2. 创建带有上下文的框架
export const ButtonFrame = styled(View, {
name: 'Button',
context: ButtonContext,
variants: {
size: {
'...size': (name, { tokens }) => ({
height: tokens.size[name],
borderRadius: tokens.radius[name],
gap: tokens.space[name].val * 0.2,
}),
},
} as const,
defaultVariants: {
size: '$medium',
},
})
// 3. 创建带有相同上下文的文本(变体会自动同步)
export const ButtonText = styled(Text, {
name: 'ButtonText',
context: ButtonContext,
variants: {
size: {
'...fontSize': (name, { font }) => ({
fontSize: font?.size[name],
}),
},
} as const,
})
// 4. 使用 withStaticProperties 组合
export const Button = withStaticProperties(ButtonFrame, {
Props: ButtonContext.Provider,
Text: ButtonText,
})
用法:
<Button size="$large">
<Button.Text>点击我</Button.Text>
</Button>
// 或者从上方覆盖默认值:
<Button.Props size="$small">
<Button><Button.Text>小</Button.Text></Button>
</Button.Props>
注意:context 模式不适用于编译器展平。用于高级组件(Button、Card),而不是基元(Stack、Text)。
用于包装组件的 styleable()
将样式化组件包装在函数组件中时,使用 .styleable() 保留变体继承:
const StyledText = styled(Text)
// 不使用 styleable - 变体继承已损坏
const BrokenWrapper = (props) => <StyledText {...props} />
// 使用 styleable - 正确
const CorrectWrapper = StyledText.styleable((props, ref) => (
<StyledText ref={ref} {...props} />
))
// 现在这样可行:
const StyledCorrectWrapper = styled(CorrectWrapper, {
variants: {
bold: { true: { fontWeight: 'bold' } },
},
})
添加额外属性
传入泛型类型参数以添加额外属性:
type ExtraProps = { icon?: React.ReactNode }
const IconText = StyledText.styleable<ExtraProps>((props, ref) => {
const { icon, ...rest } = props
return (
<XStack>
{icon}
<StyledText ref={ref} {...rest} />
</XStack>
)
})
自定义组件的 accept 属性
在非标准属性上启用令牌/主题解析:
// 对于应接受主题颜色的 SVG fill/stroke
const StyledSVG = styled(SVG, {}, {
accept: { fill: 'color', stroke: 'color' } as const,
})
// 用法:<StyledSVG fill="$blue10" />
// 对于样式对象(如 ScrollView 的 contentContainerStyle)
const MyScrollView = styled(ScrollView, {}, {
accept: { contentContainerStyle: 'style' } as const,
})
// 用法:<MyScrollView contentContainerStyle={{ padding: '$4' }} />
重要:在 accept 对象上使用 as const。
属性顺序很重要
在 styled() 中,属性顺序决定了覆盖优先级:
// backgroundColor 可以被属性覆盖
const Overridable = (props) => (
<View backgroundColor="$red10" {...props} width={200} />
)
// width 不能被覆盖(位于展开之后)
// 变体顺序也很重要:
<Component scale={3} huge /> // scale = 3(scale 在前)
<Component huge scale={3} /> // scale = 2(huge 覆盖)
反模式
动态样式破坏优化
// 错误 - 破坏编译器优化
<View style={{ width: someVariable * 2 }} />
<View backgroundColor={isDark ? '$gray1' : '$gray12'} />
// 正确 - 使用变体
const Box = styled(View, {
variants: {
dark: { true: { backgroundColor: '$gray1' }, false: { backgroundColor: '$gray12' } },
},
})
<Box dark={isDark} />
内联函数
// 错误 - 每次渲染新函数
<View onPress={() => handlePress(id)} />
// 正确 - 稳定引用
const handlePressCallback = useCallback(() => handlePress(id), [id])
<View onPress={handlePressCallback} />
错误的导入路径
// 这些是不同的包,内容不同:
import { View } from 'tamagui' // 完整 UI 套件
import { View } from '@tamagui/core' // 仅核心(更小)
import { Button } from '@tamagui/button' // 单个组件
// 选择一个方法并保持一致
混用 RN StyleSheet 和 Tamagui
// 错误 - StyleSheet 值不解析令牌
const styles = StyleSheet.create({ box: { padding: 20 } })
<View style={styles.box} backgroundColor="$blue10" />
// 正确 - 全部使用 Tamagui
<View padding="$4" backgroundColor="$blue10" />
针对 Dialog/Sheet 的 Platform.OS 分支
// 错误 - 手动平台分支
if (Platform.OS === 'web') {
return <Dialog>...</Dialog>
}
return <Sheet>...</Sheet>
// 正确 - 使用 Adapt(参见 @DIALOG_PATTERNS.md)
<Dialog>
<Dialog.Portal>...</Dialog.Portal>
<Adapt when="sm" platform="touch">
<Sheet><Adapt.Contents /></Sheet>
</Adapt>
</Dialog>
获取最新文档
获取最新 API 详情,直接获取 markdown 文档:
# 核心文档
curl -sL "https://tamagui.dev/docs/core/configuration.md"
curl -sL "https://tamagui.dev/docs/core/styled.md"
curl -sL "https://tamagui.dev/docs/core/variants.md"
curl -sL "https://tamagui.dev/docs/core/animations.md"
# 组件文档
curl -sL "https://tamagui.dev/ui/sheet.md"
curl -sL "https://tamagui.dev/ui/dialog.md"
curl -sL "https://tamagui.dev/ui/select.md"
# 完整文档索引
curl -sL "https://tamagui.dev/llms.txt"
对于 HTML 页面,使用 web-fetch 技能配合适当的选择器。
快速参考
Config v4 简写(Tailwind 对齐)
| 简写 | 属性 |
|---|---|
bg | backgroundColor |
p | padding |
m | margin |
w | width |
h | height |
br | borderRadius |
媒体查询断点
| 令牌 | 默认值 | 服务端默认值 |
|---|---|---|
$xs | 660px | true |
$sm | 800px | false |
$md | 1020px | false |
$lg | 1280px | false |
$xl | 1420px | false |
动画驱动
| 驱动 | 平台 | 用例 |
|---|---|---|
css | Web | 默认,最佳性能 |
react-native-reanimated | 原生 | 原生动画必需 |
其他模式文件
- @DIALOG_PATTERNS.md - Dialog、Sheet、Adapt、无障碍
- @FORM_PATTERNS.md - Form、Input、Label、与 zod 的验证
- @ANIMATION_PATTERNS.md - 动画驱动、enterStyle/exitStyle
- @OVERLAY_PATTERNS.md - Popover、Tooltip、Select
- @COMPILER_PATTERNS.md - 编译器优化详情
- @DESIGN_SYSTEM.md - 设计令牌和主题