Communitygithub.com

ComeOnOliver/skillshub

提供 Tamagui v4 配置、编译器优化、样式上下文和跨平台样式模式。在 Tamagui 项目(tamagui.config.ts, @tamagui 导入)中必须使用。

skillshub 是什么?

该技能为 Tamagui 框架提供了高级模式和最佳实践,涵盖 Config v4 配置、编译器优化、复合组件构建以及常见错误规避。开发者可以通过它快速搭建基于 Tamagui v4 的项目,利用简化的默认配置和 `createThemes` 创建自定义主题。技能详细介绍了 `createStyledContext` 实现复合组件(如 Button.Text)、`styleable()` 包装器保留变体继承、以及 `accept` 属性实现非标准属性上的 token/主题解析。同时,它明确指出了反模式,如动态样式破坏编译器优化、内联函数导致重复渲染以及错误的导入路径,并提供了替代方案。该技能适用于所有 Tamagui 项目,推荐在编写相关组件前阅读对应的模式文件(如 @DIALOG_PATTERNS.md)以确保正确性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/0xbigboss/tamagui-best-practices

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

本技能提供 Tamagui v1.x 超基础的模式,重点涵盖 Config v4、编译器优化、复合组件及常见错误。

必读上下文加载

使用以下组件时,请在编写代码前阅读对应的模式文件:

组件类型必读文件跨技能
Dialog、Sheet、模态覆盖层@DIALOG_PATTERNS.md
Form、Input、Label、验证@FORM_PATTERNS.mdtypescript-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 对齐)

简写属性
bgbackgroundColor
ppadding
mmargin
wwidth
hheight
brborderRadius

媒体查询断点

令牌默认值服务端默认值
$xs660pxtrue
$sm800pxfalse
$md1020pxfalse
$lg1280pxfalse
$xl1420pxfalse

动画驱动

驱动平台用例
cssWeb默认,最佳性能
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 - 设计令牌和主题

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Next.js 16+ uses App Router with Server Components by default. Client Components are only used when interactivity is needed (hooks, event handlers, browser APIs).

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能