此技能提供了超越基礎的 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 | |
| 設計 Token、主題 | @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 搭配色板/強調色/子主題:
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: { /* ... */ },
},
})
Token 與主題語法
$ 前綴規則
- Props(屬性):在 token 參考中使用
$前綴:<Text color="$color" fontSize="$4" /> - 主題鍵:在主體定義中存取時不使用
$:{ color: palette[11] } - 變體中的 Token 存取:使用
tokens.size[name]模式
變體展開運算子
特殊的展開運算子將 token 類別映射到變體值:
const Button = styled(View, {
variants: {
size: {
// 映射 size token:$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 token
'...fontSize': (name, { font }) => ({
fontSize: font?.size[name],
}),
},
} as const,
})
重要:在變體物件上使用 as const,直到 TypeScript 支援推斷的 const 泛型。
使用 createStyledContext 建立複合元件
用於像 <Button><Button.Text>Click</Button.Text></Button> 這樣的複合 API:
import {
SizeTokens,
View,
Text,
createStyledContext,
styled,
withStaticProperties,
} from '@tamagui/core'
// 1. 建立帶有共享變體型別的 context
export const ButtonContext = createStyledContext<{ size: SizeTokens }>({
size: '$medium',
})
// 2. 建立帶有 context 的框架
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. 建立帶有相同 context 的文字(變體自動同步)
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()
將 styled 元件封裝在函式元件中時,請使用 .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' } },
},
})
加入額外的 Props
傳入泛型型別參數以加入額外的 props:
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 Prop
啟用對非標準 props 的 token/theme 解析:
// 對於應接受主題顏色的 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。
Prop 順序很重要
在 styled() 中,prop 順序決定覆蓋優先權:
// backgroundColor 可以被 props 覆蓋
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 的值無法解析 token
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 |
媒體查詢中斷點
| Token | 預設值 | 伺服器預設值 |
|---|---|---|
$xs | 660px | true |
$sm | 800px | false |
$md | 1020px | false |
$lg | 1280px | false |
$xl | 1420px | false |
動畫驅動程式
| 驅動程式 | 平台 | 使用案例 |
|---|---|---|
css | Web | 預設,最佳效能 |
react-native-reanimated | Native | 原生動畫所需 |
其他模式檔案
- @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 - 設計 Token 與主題設定