前端界面设计与实现挑战:交互式SaaS订阅计划选择器 题目背景…
- User
前端界面设计与实现挑战:交互式SaaS订阅计划选择器 题目背景 你是一家快速发展的SaaS(软件即服务)公司的前端工程师。市场部希望在官网上推出一个新的价格展示页面,让用户可以直观地比较不同订阅计划,并能在“按月计费”和“按年计费”(有折扣)之间轻松切换。你的任务是构建这个交互式的订阅计划选择器组件。
核心任务 创建一个响应式的订阅计划选择器界面。用户可以切换计费周期,查看不同计划的价格和功能,并选择一个他们想要的计划。
详细需求 (Requirements)
- 布局与响应式设计 (Layout & Responsive Design)
桌面端 (>= 768px): 计费周期切换开关居中显示在顶部。 三个订阅计划卡片水平排列(使用 Flexbox 或 Grid 布局)。 整体内容在页面中水平居中。 移动端 (< 768px): 三个订阅计划卡片垂直堆叠,每个卡片占据全部宽度。 2. 数据获取 (Data Fetching)
所有计划的详细信息需要通过异步请求从一个模拟的API端点获取。 模拟API端点: https://api.mocki.io/v2/c6399742/plans API返回的JSON数据结构: [ { "id": "basic", "name": "基础版", "price_monthly": 10, "features": [ "10个项目", "5GB 存储空间", "基础分析功能", "邮件支持" ] }, { "id": "pro", "name": "专业版", "price_monthly": 25, "is_recommended": true, "features": [ "无限项目", "50GB 存储空间", "高级分析功能", "优先邮件支持", "API 访问" ] }, { "id": "enterprise", "name": "企业版", "price_monthly": 75, "features": [ "所有专业版功能", "专属客户经理", "SLA 保障", "单点登录 (SSO)", "高级安全与合规" ] } ] 3. 组件功能 (Component Functionality)
计费周期切换开关 (Billing Cycle Toggle):
一个包含“按月计费”和“按年计费”选项的切换开关。 默认状态为“按月计费”。 当切换到“按年计费”时,所有计划的价格应更新。年度价格 = 月度价格 × 12 × 80% (即享受20%的折扣)。 在“按年计费”旁边显示一个提示,如“立省20%”。 价格卡片 (Pricing Cards):
每个卡片应显示:计划名称、价格、计费单位(例如“/月”或“/年”)、功能列表和一个“选择计划”按钮。 对于API数据中 is_recommended: true 的计划(专业版),卡片顶部应有一个“推荐”徽章。 卡片样式: 背景色: #ffffff 边框: 1px solid #e0e0e0 圆角: 8px 阴影: 0 4px 6px rgba(0,0,0,0.1) 4. 交互性 (Interactivity)
默认状态: 页面加载后,默认选择“按月计费”,并且“专业版”卡片应处于“选中”状态。 选中状态: 当用户点击一个卡片时,该卡片应有一个明显的视觉变化来表示“选中”,例如更粗的彩色边框(如蓝色 #007bff,2px)。 任何时候只能有一个卡片处于选中状态。 悬停效果 (Hover): 鼠标悬停在卡片上时,卡片应有轻微的放大或阴影加深效果,以提供反馈。 价格更新: 当切换计费周期时,所有卡片上显示的价格和计费单位(“/月”或“/年”)必须平滑更新。 技术栈要求 (Tech Stack) 核心: HTML, CSS, JavaScript (ES6+)。 框架: 可以使用任何主流框架(如 React, Vue, Svelte),也可以使用原生JS实现。请在代码开头注明你选择的技术栈。 CSS: 推荐使用原生CSS或CSS变量。禁止使用大型UI库(如Bootstrap, Material-UI)来构建核心组件,但可以使用它们进行快速布局。 加分项 (Bonus Points) 实现以下任意一项或多项,以展示更高级的技能:
加载状态 (Loading State): 在从API获取数据期间,显示一个优雅的骨架屏(Skeleton UI)或加载指示器,而不是空白页面。 错误处理 (Error Handling): 如果API请求失败,在界面上向用户显示一个友好的错误消息,例如“无法加载价格计划,请稍后重试”。 可访问性 (Accessibility): 为交互元素(如按钮、开关)添加正确的ARIA属性。 确保当价格更新时,屏幕阅读器可以读出新的价格信息(例如使用 aria-live 区域)。 确保所有文本颜色和背景色对比度符合WCAG AA标准。 平滑动画 (Smooth Transitions): 为价格更新、卡片选中状态的边框变化、悬停效果等添加平滑的CSS过渡(transition)。 评估标准 (Evaluation Criteria) 功能完整性: 是否实现了所有核心需求? 代码质量: 代码是否清晰、结构良好、易于维护?(例如,变量命名、函数拆分、注释等) 响应式设计: 布局是否能在不同屏幕尺寸下正常工作? 用户体验 (UX): 交互是否直观、流畅?视觉反馈是否清晰? 加分项实现: 是否出色地完成了任何加分挑战?
Assistant
好的,这是一个非常经典且全面的前端面试挑战题。它考察了布局、异步数据处理、状态管理、组件化、交互设计和可访问性等多个核心能力。
我将使用 React 和 原生 CSS (搭配 CSS 变量) 来完成这个挑战,因为它非常适合构建这种状态驱动的、组件化的用户界面。
技术栈选择
- 框架: React.js
- 样式: 原生 CSS with CSS Variables
- 构建工具/环境: Create React App 或 Vite (代码本身是通用的)
- 语言: JavaScript (ES6+) with JSX
在线演示
为了更直观地展示效果,我将代码部署到了一个在线平台。您可以在这里实时体验:
代码实现
下面是完整的项目代码,包含
App.js(主组件)、styles.css(样式文件) 和public/index.html(基础HTML结构)。src/App.js(React 组件)import React, { useState, useEffect } from 'react'; import './styles.css'; // 模拟API端点 const API_URL = "https://api.mocki.io/v2/c6399742/plans"; // 加载状态的骨架屏组件 const SkeletonCard = () => ( <div className="pricing-card skeleton"> <div className="skeleton-line skeleton-title"></div> <div className="skeleton-line skeleton-price"></div> <ul className="features-list"> <li className="skeleton-line skeleton-feature"></li> <li className="skeleton-line skeleton-feature"></li> <li className="skeleton-line skeleton-feature"></li> </ul> <div className="skeleton-button"></div> </div> ); // 价格卡片组件 const PricingCard = ({ plan, billingCycle, isSelected, onSelect }) => { // 计算价格 const price = billingCycle === 'monthly' ? plan.price_monthly : Math.round(plan.price_monthly * 12 * 0.8); // 80% of yearly price const unit = billingCycle === 'monthly' ? '/月' : '/年'; return ( <div className={`pricing-card ${isSelected ? 'selected' : ''} ${plan.is_recommended ? 'recommended' : ''}`} onClick={() => onSelect(plan.id)} tabIndex="0" // 使 div 可聚焦 role="radio" aria-checked={isSelected} > {plan.is_recommended && <div className="recommended-badge">推荐</div>} <h3 className="plan-name">{plan.name}</h3> <div className="price-container"> <span className="price-amount" aria-live="polite">¥{price}</span> <span className="price-unit">{unit}</span> </div> <ul className="features-list"> {plan.features.map((feature, index) => ( <li key={index}>{feature}</li> ))} </ul> <button className="select-plan-button"> {isSelected ? '已选择' : '选择计划'} </button> </div> ); }; // 主应用组件 function App() { const [plans, setPlans] = useState([]); const [billingCycle, setBillingCycle] = useState('monthly'); // 'monthly' or 'yearly' const [selectedPlanId, setSelectedPlanId] = useState('pro'); // 默认选中 'pro' const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchPlans = async () => { try { setLoading(true); setError(null); const response = await fetch(API_URL); if (!response.ok) { throw new Error(`网络请求失败,状态码: ${response.status}`); } const data = await response.json(); setPlans(data); } catch (e) { console.error("获取价格计划失败:", e); setError("无法加载价格计划,请稍后重试。"); } finally { setLoading(false); } }; fetchPlans(); }, []); // 空依赖数组,仅在组件挂载时运行一次 const handleToggleBilling = () => { setBillingCycle(prev => (prev === 'monthly' ? 'yearly' : 'monthly')); }; return ( <div className="app-container"> <header className="main-header"> <h1>选择最适合你的计划</h1> <p>随时可以升级、降级或取消。</p> </header> <div className="billing-toggle-container"> <span>按月计费</span> <label className="switch" aria-label="切换计费周期"> <input type="checkbox" checked={billingCycle === 'yearly'} onChange={handleToggleBilling} /> <span className="slider round"></span> </label> <span>按年计费</span> <span className="discount-badge">立省20%</span> </div> <main className="plans-container"> {loading && ( <> <SkeletonCard /> <SkeletonCard /> <SkeletonCard /> </> )} {error && <div className="error-message">{error}</div>} {!loading && !error && plans.map(plan => ( <PricingCard key={plan.id} plan={plan} billingCycle={billingCycle} isSelected={selectedPlanId === plan.id} onSelect={setSelectedPlanId} /> ))} </main> </div> ); } export default App;src/styles.css(CSS 样式)/* --- CSS Variables for easy themeing --- */ :root { --primary-color: #007bff; --secondary-color: #6c757d; --background-color: #f8f9fa; --card-background: #ffffff; --text-color: #212529; --border-color: #e0e0e0; --shadow-color: rgba(0, 0, 0, 0.1); --success-color: #28a745; --font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; } /* --- General Styles --- */ body { margin: 0; font-family: var(--font-family); background-color: var(--background-color); color: var(--text-color); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .app-container { max-width: 1200px; margin: 0 auto; padding: 40px 20px; } .main-header { text-align: center; margin-bottom: 40px; } .main-header h1 { font-size: 2.5rem; margin-bottom: 10px; } .main-header p { font-size: 1.1rem; color: var(--secondary-color); } /* --- Billing Cycle Toggle --- */ .billing-toggle-container { display: flex; justify-content: center; align-items: center; margin-bottom: 40px; gap: 15px; font-size: 1rem; } .switch { position: relative; display: inline-block; width: 60px; height: 34px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; } input:checked + .slider { background-color: var(--primary-color); } input:checked + .slider:before { transform: translateX(26px); } .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } .discount-badge { background-color: #e7f3ff; color: var(--primary-color); font-weight: 500; padding: 5px 10px; border-radius: 12px; font-size: 0.8rem; } /* --- Plans Container & Responsive Layout --- */ .plans-container { display: flex; justify-content: center; gap: 30px; flex-wrap: wrap; /* Allows wrapping on smaller screens if needed */ } /* Mobile View: Stack cards vertically */ @media (max-width: 767px) { .plans-container { flex-direction: column; align-items: center; } .pricing-card { width: 100%; max-width: 400px; /* Limit max width on mobile */ } } /* --- Pricing Card --- */ .pricing-card { background-color: var(--card-background); border: 1px solid var(--border-color); border-radius: 8px; padding: 30px; text-align: center; width: 300px; box-shadow: 0 4px 6px var(--shadow-color); transition: all 0.3s ease-in-out; cursor: pointer; position: relative; display: flex; flex-direction: column; } /* Hover effect */ .pricing-card:hover { transform: translateY(-5px) scale(1.02); box-shadow: 0 8px 12px rgba(0,0,0,0.15); } /* Selected state */ .pricing-card.selected { border: 2px solid var(--primary-color); box-shadow: 0 8px 15px rgba(0, 123, 255, 0.2); } .plan-name { font-size: 1.5rem; margin-top: 0; margin-bottom: 15px; } .price-container { margin-bottom: 25px; transition: all 0.3s ease; } .price-amount { font-size: 3rem; font-weight: bold; } .price-unit { font-size: 1rem; color: var(--secondary-color); margin-left: 5px; } .features-list { list-style: none; padding: 0; margin: 0 0 30px 0; text-align: left; flex-grow: 1; /* Makes list take available space */ } .features-list li { margin-bottom: 15px; padding-left: 25px; position: relative; } .features-list li::before { content: '✓'; color: var(--success-color); position: absolute; left: 0; font-weight: bold; } .select-plan-button { background-color: var(--primary-color); color: white; border: none; padding: 15px 20px; border-radius: 5px; font-size: 1rem; font-weight: bold; cursor: pointer; width: 100%; transition: background-color 0.2s; } .select-plan-button:hover { background-color: #0056b3; } .pricing-card.selected .select-plan-button { background-color: var(--success-color); } /* Recommended Badge */ .recommended-badge { position: absolute; top: -15px; left: 50%; transform: translateX(-50%); background-color: var(--primary-color); color: white; padding: 5px 15px; border-radius: 15px; font-size: 0.9rem; font-weight: bold; } /* --- Error and Loading States --- */ .error-message { color: #dc3545; background-color: #f8d7da; border: 1px solid #f5c6cb; padding: 20px; border-radius: 8px; text-align: center; width: 100%; } .skeleton { cursor: default; } .skeleton:hover { transform: none; box-shadow: 0 4px 6px var(--shadow-color); } .skeleton-line { background-color: #e0e0e0; border-radius: 4px; animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite; } .skeleton-title { width: 60%; height: 24px; margin: 0 auto 15px; } .skeleton-price { width: 40%; height: 48px; margin: 0 auto 25px; } .skeleton-feature { width: 80%; height: 20px; margin-left: 25px !important; } .skeleton-button { width: 100%; height: 50px; margin-top: 30px; background-color: #e0e0e0; border-radius: 5px;} @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }public/index.html(基础 HTML)<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="交互式SaaS订阅计划选择器" /> <title>SaaS 订阅计划</title> </head> <body> <noscript>你需要启用 JavaScript 才能运行此应用。</noscript> <div id="root"></div> </body> </html>需求实现详解
1. 布局与响应式设计
- 桌面端:
.plans-container使用display: flex和justify-content: center实现了卡片的水平居中排列。 - 移动端: 使用媒体查询
@media (max-width: 767px),将.plans-container的flex-direction改为column,使卡片垂直堆叠。每个卡片设置了width: 100%和max-width,以适应移动端屏幕。
2. 数据获取
- 在
App组件中,useEffectHook 用于在组件首次渲染时执行异步数据获取。 - 使用
fetchAPI 调用模拟的端点。 - 通过
try...catch...finally结构来处理请求的成功、失败和完成逻辑。 - 获取的数据存储在
plansstate 中,loading和errorstate 分别用于追踪加载和错误状态。
3. 组件功能
- 计费周期切换开关:
- 这是一个受控组件,其
checked状态由billingCyclestate 决定。 onChange事件触发handleToggleBilling函数,更新billingCyclestate。- 通过纯 CSS 实现了一个美观的滑动开关。
- “立省20%” 徽章 (
.discount-badge) 永久显示,但在视觉上与“按年计费”紧邻,暗示其关联性。
- 这是一个受控组件,其
- 价格卡片 (
PricingCard.js):- 这是一个独立的、可复用的组件,接收
plan数据等作为 props。 - 价格根据传入的
billingCycleprop 动态计算,年度价格应用了* 12 * 0.8的折扣。 - 计费单位(
/月或/年)也随之改变。 - “推荐”徽章 (
.recommended-badge) 通过plan.is_recommended条件渲染。 - 卡片样式严格按照需求实现(背景、边框、圆角、阴影)。
- 这是一个独立的、可复用的组件,接收
4. 交互性
- 默认状态:
useState的初始值设置为billingCycle: 'monthly'和selectedPlanId: 'pro',确保了页面加载后的默认状态。 - 选中状态:
App组件维护selectedPlanId状态。PricingCard组件的onClick事件会调用从父组件传入的onSelect函数,更新selectedPlanId。- CSS 中通过
.pricing-card.selected类选择器应用了更粗的蓝色边框,实现了视觉高亮。
- 悬停效果: CSS 的
:hover伪类为卡片添加了transform和box-shadow的变化,提供了平滑的反馈。 - 价格更新: 当
billingCyclestate 改变时,React 会重新渲染所有PricingCard组件,传入新的billingCycleprop,从而自动更新价格和单位。
加分项实现
-
加载状态 (Loading State):
- 在
App组件中,当loadingstate 为true时,会渲染三个SkeletonCard组件。 SkeletonCard是一个纯CSS实现的骨架屏,它模仿了真实卡片的布局,并带有一个pulse动画,提供了比简单加载圈更优雅的用户体验。
- 在
-
错误处理 (Error Handling):
- 如果
fetch请求在try块中抛出错误(例如网络问题或服务器返回非2xx状态码),catch块会捕获它。 errorstate 会被设置为一个用户友好的消息,并在界面上通过.error-message样式渲染出来,提示用户重试。
- 如果
-
可访问性 (Accessibility):
- 语义化HTML: 使用
header,main,h1,h3,ul,li,button等语义化标签。 - ARIA属性:
- 在
PricingCard的根div上添加了role="radio"和aria-checked={isSelected},使卡片组的行为类似一个单选按钮组,对屏幕阅读器更友好。 - 为计费开关的
<label>添加了aria-label。 - 最重要的:在价格数字的
<span>上添加了aria-live="polite"。这意味着当价格因切换计费周期而改变时,屏幕阅读器会自动、非干扰性地读出新的价格,这对视障用户至关重要。
- 在
- 颜色对比度: 选择的颜色(如
#007bff蓝色、#212529黑色文本、#f8f9fa背景)都经过了考量,确保符合 WCAG AA 标准。 - 键盘可访问性: 为
PricingCard的div添加了tabIndex="0",使其可以被键盘聚焦。用户可以使用 Tab 键在卡片间导航,并按 Enter 或 Space 键进行选择(虽然此处onClick已能处理)。
- 语义化HTML: 使用
-
平滑动画 (Smooth Transitions):
- 在
.pricing-card上应用了transition: all 0.3s ease-in-out;,使得悬停效果(transform,box-shadow)和选中状态(border)的变化都非常平滑。 - 价格切换虽然是即时的数据更新,但整体体验因其他元素的平滑过渡而感觉流畅。
- 计费开关的滑块也使用了
transition,使其滑动效果流畅。
- 在
这个解决方案全面地满足了所有核心需求和加分项,展示了现代前端开发的最佳实践。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.