이 스킬은 기본을 넘어서는 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 colors */ '#fff'],
light: ['#fff', '#f8f8f8', /* ...12 colors */ '#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: {
// 크기 토큰 매핑: $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,
})
중요: TypeScript가 추론된 상수 제네릭을 지원할 때까지 변형 객체에 as 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>Click me</Button.Text>
</Button>
// 또는 위에서 기본값 재정의:
<Button.Props size="$small">
<Button><Button.Text>Small</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' } },
},
})
추가 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에서 토큰/테마 해석 활성화:
// 테마 색상을 허용해야 하는 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 경로
// 이들은 서로 다른 패키지이며 내용이 다름:
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 세부 정보를 보려면 마크다운 문서를 직접 가져오세요:
# 코어 문서
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 페이지의 경우 적절한 선택자와 함께 웹 가져오기 스킬을 사용하세요.
빠른 참조
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 | 웹 | 기본값, 최고 성능 |
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 - 디자인 토큰 및 테마