Communitygithub.com

前端组件技能

指导创建遵循服务端/客户端组件模式的 Next.js 组件,并利用现有组件结构。

前端组件技能 是什么?

这项技能为使用 Next.js 16+ 和 App Router 的开发者提供了全面的指导。它强调了服务端组件作为默认选择,而客户端组件仅在需要交互性(如使用 React 钩子、事件处理程序或浏览器 API)时使用。该技能文档详细介绍了关键的模式,包括服务端与客户端组件的选择标准代码结构模板、受保护路由的实现(涉及认证检查、加载状态和重定向逻辑)、加载微调器的设计(支持多种尺寸和颜色,并具备可访问性标签),以及表单处理的最佳实践(包含客户端验证、错误处理和用户反馈机制)。此外,还涵盖了 Tailwind CSS 的实用工具类样式策略、符合 WCAG 2.1 AA 标准的无障碍访问模式、文件命名约定,以及像拖放和撤销/重做这样的高级模式。它旨在帮助开发者编写可维护、高性能且符合规范的前端代码。

兼容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/asmayaseen/frontend-component

在你喜欢的 AI 中提问

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

文档

前端组件技能 是做什么的?

目的:指导创建遵循服务端/客户端组件模式并利用现有组件结构的 Next.js 组件。

概述

Next.js 16+ 默认使用带有服务端组件的 App Router。仅在需要交互性(钩子、事件处理程序、浏览器 API)时才使用客户端组件。

服务端与客户端组件

服务端组件(默认)

何时使用:

  • 页面和布局
  • 静态内容
  • 从 API 获取数据(如果可能)
  • SEO 优化内容

模式:

// 没有 "use client" 指令
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "页面标题",
};

export default function PageComponent() {
  return <div>静态内容</div>;
}

示例:frontend/app/layout.tsx, frontend/app/page.tsx

客户端组件(需要时使用)

何时使用:

  • 交互元素(按钮、表单、输入框)
  • 事件处理程序(onClick、onChange 等)
  • React 钩子(useState、useEffect、useRouter 等)
  • 浏览器 API(localStorage、window、document 等)
  • 实时更新
  • 拖放功能

模式:

"use client"; // 必须是第一行

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";

interface ComponentProps {
  prop1: string;
  prop2?: number;
}

export default function ComponentName({ prop1, prop2 }: ComponentProps) {
  const router = useRouter();
  const [state, setState] = useState("");

  useEffect(() => {
    // 副作用
  }, []);

  return <div>{/* 组件 JSX */}</div>;
}

示例:frontend/components/ProtectedRoute.tsx, frontend/app/signup/page.tsx

组件结构模板

"use client"; // 仅当是客户端组件时

/**
 * 组件名称
 *
 * 简要描述此组件的功能
 */

import { useState, useEffect } from "react";
import { ComponentType } from "@/types";
import { cn } from "@/lib/utils";

interface ComponentProps {
  prop1: string;
  prop2?: number;
  className?: string;
}

export default function ComponentName({ prop1, prop2, className }: ComponentProps) {
  // 状态
  const [state, setState] = useState("");

  // 副作用
  useEffect(() => {
    // 副作用逻辑
  }, []);

  // 事件处理
  const handleClick = () => {
    // 处理程序逻辑
  };

  // 渲染
  return (
    <div className={cn("base-classes", className)}>
      {/* 组件内容 */}
    </div>
  );
}

特定组件模式

1. 受保护路由模式

源自:frontend/components/ProtectedRoute.tsx

"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { isAuthenticated } from "@/lib/auth";
import LoadingSpinner from "./LoadingSpinner";

interface ProtectedRouteProps {
  children: React.ReactNode;
}

export default function ProtectedRoute({ children }: ProtectedRouteProps) {
  const router = useRouter();
  const [isAuthorized, setIsAuthorized] = useState(false);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    async function checkAuth() {
      try {
        const authenticated = await isAuthenticated();

        if (!authenticated) {
          const currentPath = window.location.pathname;
          if (currentPath !== "/signin") {
            sessionStorage.setItem("redirectAfterLogin", currentPath);
          }
          router.push("/signin");
        } else {
          setIsAuthorized(true);
        }
      } catch (error) {
        console.error("Auth check failed:", error);
        router.push("/signin");
      } finally {
        setIsChecking(false);
      }
    }

    checkAuth();
  }, [router]);

  if (isChecking) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <LoadingSpinner size="large" />
      </div>
    );
  }

  if (!isAuthorized) {
    return null;
  }

  return <>{children}</>;
}

模式:

  • 在组件挂载时检查认证状态
  • 检查期间显示加载微调器
  • 将预期目标页面存储在 sessionStorage 中
  • 如果未认证,重定向到 /signin
  • 仅在授权时渲染子组件

2. 加载微调器模式

源自:frontend/components/LoadingSpinner.tsx

interface LoadingSpinnerProps {
  size?: "small" | "medium" | "large";
  color?: string;
  label?: string;
}

export default function LoadingSpinner({
  size = "medium",
  color = "blue",
  label = "Loading...",
}: LoadingSpinnerProps) {
  const sizeClasses = {
    small: "w-4 h-4 border-2",
    medium: "w-8 h-8 border-3",
    large: "w-12 h-12 border-4",
  };

  const colorClasses = {
    blue: "border-blue-600 border-t-transparent",
    gray: "border-gray-600 border-t-transparent",
    white: "border-white border-t-transparent",
  };

  const spinnerClass = `${sizeClasses[size]} ${
    colorClasses[color as keyof typeof colorClasses] || colorClasses.blue
  } rounded-full animate-spin`;

  return (
    <div
      className="flex items-center justify-center"
      role="status"
      aria-label={label}
      aria-live="polite"
    >
      <div className={spinnerClass}></div>
      <span className="sr-only">{label}</span>
    </div>
  );
}

模式:

  • 多种尺寸(small、medium、large)
  • 多种颜色(blue、gray、white)
  • 无障碍访问标签(role="status"、aria-label、aria-live)
  • 使用 sr-only 类为屏幕阅读器提供文本

3. 表单处理模式

源自:frontend/app/signup/page.tsx

"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api";
import { isValidEmail, getPasswordStrength } from "@/lib/utils";

export default function SignupPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(false);
  const [apiError, setApiError] = useState("");

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = "Name is required";
    }

    if (!formData.email.trim()) {
      newErrors.email = "Email is required";
    } else if (!isValidEmail(formData.email)) {
      newErrors.email = "Please enter a valid email address";
    }

    // More validation...

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setApiError("");

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      const response = await api.signup(formData);
      if (response.success) {
        router.push("/dashboard");
      } else {
        setApiError(response.message || "Signup failed");
      }
    } catch (error: any) {
      setApiError(error.message || "An error occurred");
    } finally {
      setIsLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    // Clear error for this field when user starts typing
    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: "" }));
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
    </form>
  );
}

模式:

  • 分别为表单数据、错误、加载状态和 API 错误设置状态
  • 返回布尔值的验证函数
  • 输入变化时清除错误
  • 提交期间设置加载状态
  • 使用 try-catch 进行错误处理
  • 成功后重定向

4. 吐司通知模式

源自:frontend/components/ToastNotification.tsx

"use client";

import { useEffect, useState } from "react";
import { ToastMessage, ToastType } from "@/types";

export function useToast() {
  const [toasts, setToasts] = useState<ToastMessage[]>([]);

  const showToast = (type: ToastType, message: string, duration?: number) => {
    const id = `toast-${Date.now()}-${Math.random()}`;
    const newToast: ToastMessage = {
      id,
      type,
      message,
      duration,
    };
    setToasts((prev) => [...prev, newToast]);
  };

  const dismissToast = (id: string) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  };

  return {
    toasts,
    showToast,
    dismissToast,
    success: (message: string, duration?: number) => showToast("success", message, duration),
    error: (message: string, duration?: number) => showToast("error", message, duration),
    // ...
  };
}

模式:

  • 用于通知管理的自定义钩子
  • 通过持续时间自动关闭
  • 堆叠多个通知
  • 辅助方法(成功、错误、警告、信息)

Tailwind CSS 模式

1. 仅使用工具类

<div className="flex items-center justify-center gap-4 p-6 bg-white rounded-lg shadow-md">

模式:使用 Tailwind 工具类,不使用内联样式

2. 使用 cn() 工具添加条件类

import { cn } from "@/lib/utils";

<div className={cn(
  "base-classes",
  condition && "conditional-classes",
  className // Allow prop override
)}>

模式:使用 @/lib/utils 中的 cn() 处理条件类

3. 暗色模式支持

<div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">

模式:使用 dark: 前缀添加暗色模式样式

4. 响应式设计

<div className="w-full sm:w-1/2 md:w-1/3 lg:w-1/4">

模式:使用断点前缀(sm:、md:、lg:、xl:)

无障碍访问模式(WCAG 2.1 AA)

1. ARIA 标签

<button aria-label="Close dialog">×</button>
<div role="status" aria-live="polite" aria-label="Loading...">

模式:始终为纯图标按钮提供 aria-label

2. 语义化 HTML

<nav>
  <ul>
    <li><a href="/">Home</a></li>
  </ul>
</nav>

模式:使用语义化 HTML 元素(nav、main、section、article 等)

3. 键盘导航

<button
  onClick={handleClick}
  onKeyDown={(e) => {
    if (e.key === "Enter" || e.key === " ") {
      handleClick();
    }
  }}
>

模式:确保所有交互元素支持键盘无障碍访问

4. 屏幕阅读器文本

<span className="sr-only">Loading content</span>

模式:使用 sr-only 类提供屏幕阅读器专用文本

5. 焦点管理

<input
  autoFocus
  className="focus:outline-none focus:ring-2 focus:ring-blue-500"
/>

模式:始终提供可见的焦点指示器

文件命名约定

  • 页面:kebab-case(例如 signup.tsx, signin.tsx)
  • 组件:PascalCase(例如 TaskList.tsx, TaskItem.tsx)
  • 布局:layout.tsx
  • 错误页面:error.tsx, not-found.tsx

符合的要求

  • FR-033:Next.js 16+ App Router 结构 ✅
  • FR-034:默认使用服务端组件,需要时使用客户端组件 ✅
  • FR-035:错误边界 ✅
  • FR-036:WCAG 2.1 AA 合规 ✅
  • FR-037:TypeScript 严格模式 ✅
  • FR-038:Prettier 格式化 ✅
  • FR-039:ESLint 规则 ✅

参考

  • 规格说明:specs/002-frontend-todo-app/spec.md - 组件规格
  • 现有组件:frontend/components/*.tsx - 组件示例
  • 现有页面:frontend/app/*.tsx - 页面示例

高级组件模式

1. 拖放模式(阶段 7 - T065)

库:@dnd-kit/core

"use client";

import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";

export default function SortableTaskList({ tasks, onReorder }: Props) {
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      onReorder(active.id, over.id);
    }
  };

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={tasks.map(t => t.id)} strategy={verticalListSortingStrategy}>
        {tasks.map(task => (
          <SortableTaskItem key={task.id} task={task} />
        ))}
      </SortableContext>
    </DndContext>
  );
}

模式:使用 @dnd-kit/core 实现拖放,在拖放结束时处理重新排序

2. 撤销/重做模式(阶段 7 - T066)

"use client";

import { useReducer } from "react";

interface HistoryState<T> {
  past: T[];
  present: T;
  future: T[];
}

function historyReducer<T>(state: HistoryState<T>, action: { type: string; newPresent?: T }): HistoryState<T> {
  const { past, present, future } = state;

  switch (action.type) {
    case "UNDO":
      if (past.length === 0) return state;
      return {
        past: past.slice(0, past.length - 1),
        present: past[past.length - 1],
        future: [present, ...future],
      };
    case "REDO":
      if (future.length === 0) return state;
      return {
        past: [...past, present],
        present: future[0],
        future: future.slice(1),
      };
    case "SET":
      if (action.newPresent === present) return state;
      return {
        past: [...past, present],
        present: action.newPresent!,
        future: [],
      };
    default:
      return state;
  }
}

export function useHistory<T>(initialPresent: T) {
  const [state, dispatch] = useReducer(historyReducer, {
    past: [],
    present: initialPresent,
    future: [],
  });

  const undo = () => dispatch({ type: "UNDO" });
  const redo = () => dispatch({ type: "REDO" });
  const set = (newPresent: T) => dispatch({ typ

…

[内容过长,已截断]

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

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

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

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

相关技能