Skip to content

前端组件设计规范

组件职责原则

  • 单一职责:每个组件只做一件事
  • Props 是公开 API,保持最小化并提供合理默认值
  • 业务逻辑放入 Hook(React)或 Composable(Vue),组件只负责渲染

Props 设计

  • 用 TypeScript 明确定义 Props 类型
  • 事件处理 prop 以 on 开头:onSubmitonChange
  • 避免传整个大对象,只透传必要字段
  • 组件内部状态不应通过 Props 暴露

拆分时机

  • 超过 150 行时考虑拆分
  • 可复用的 UI 片段提取为独立组件
  • 容器组件(数据获取)与展示组件(纯渲染)分离

状态管理

  • 本地状态优先(useState / ref
  • 跨层级共享使用 Context 或状态管理库
  • 避免把仅局部使用的状态放入全局 Store

示例(React)

tsx
interface UserCardProps {
  userId: string;
  onEdit?: (id: string) => void;
}

const UserCard: React.FC<UserCardProps> = ({ userId, onEdit }) => {
  const { user, loading } = useUser(userId); // 业务逻辑在 Hook 中
  if (loading) return <Skeleton />;
  return <Card title={user.name} onAction={() => onEdit?.(userId)} />;
};

Power By 数字海南