组件化开发是一种将复杂系统分解为独立、可复用、可组合的组件的软件开发方法。每个组件包含自己的逻辑、样式和结构,可以独立开发、测试和维护,然后组合成完整的应用。
组件/
├── index.tsx # 组件入口
├── Component.tsx # 组件逻辑
├── Component.module.css # 样式文件
├── Component.test.tsx # 单元测试
└── Component.stories.tsx # Storybook 故事
// Button.jsx
import React from 'react'
import './Button.css'
export function Button({ children, variant = 'primary', ...props }) {
return (
<button className={`btn btn-${variant}`} {...props}>
{children}
</button>
)
}
// 使用
<Button variant="secondary" onClick={() => {}}>
提交
</Button>
<!-- Button.vue -->
<template>
<button :class="['btn', `btn-${variant}`]" v-bind="$attrs">
<slot />
</button>
</template>
<script>
export default {
name: 'Button',
props: {
variant: {
type: String,
default: 'primary'
}
}
}
</script>
<style scoped>
.btn {
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
// 父组件
function Parent() {
return <Child name="Alice" age={25} />
}
// 子组件
function Child(props) {
return <div>{props.name}, {props.age}</div>
}
// 子组件
function Child({ onSubmit }) {
const handleClick = () => {
onSubmit('数据')
}
return <button onClick={handleClick}>提交</button>
}
// 父组件
function Parent() {
const handleSubmit = (data) => {
console.log('收到:', data)
}
return <Child onSubmit={handleSubmit} />
}
// 创建 Context
const ThemeContext = React.createContext()
// 提供者
function ThemeProvider({ children }) {
return (
<ThemeContext.Provider value="dark">
{children}
</ThemeContext.Provider>
)
}
// 消费者
function Button() {
const theme = useContext(ThemeContext)
return <button className={theme}>按钮</button>
}
// Redux / Zustand
const useStore = create((set) => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 }))
}))
function Component() {
const { count, increment } = useStore()
return <button onClick={increment}>{count}</button>
}