# 前端开发模式
适用于 React、Next.js 和高性能用户界面的现代前端模式。
## 组件模式
### 组合优于继承
typescript
// ✅ 推荐:组件组合
interface CardProps {
children: React.ReactNode
variant?: 'default' | 'outlined'
}
export function Card({ children, variant = 'default' }: CardProps) {
return
{children}
}
export function CardHeader({ children }: { children: React.ReactNode }) {
return
{children}
}
export function CardBody({ children }: { children: React.ReactNode }) {
return
{children}
}
// 用法
Title
Content
### 复合组件
typescript
interface TabsContextValue {
activeTab: string
setActiveTab: (tab: string) => void
}
const TabsContext = createContext(undefined)
export function Tabs({ children, defaultTab }: {
children: React.ReactNode
defaultTab: string
}) {
const [activeTab, setActiveTab] = useState(defaultTab)
return (
{children}
)
}
export function TabList({ children }: { children: React.ReactNode }) {
return
{children}
}
export function Tab({ id, children }: { id: string, children: React.ReactNode }) {
const context = useContext(TabsContext)
if (!context) throw new Error('Tab must be used within Tabs')
return (
)
}
// 用法
Overview
Details
### Render Props 模式
typescript
interface DataLoaderProps {
url: string
children: (data: T | null, loading: boolean, error: Error | null) => React.ReactNode
}
export function DataLoader({ url, children }: DataLoaderProps) {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false))
}, [url])
return <