react如何重用组件
重用组件的核心方法
通过Props传递数据
父组件通过props向子组件传递数据或配置,子组件根据props渲染不同内容。例如:
function Button({ text, color }) {
return <button style={{ backgroundColor: color }}>{text}</button>;
}
// 重用示例
<Button text="提交" color="blue" />
<Button text="取消" color="red" />
使用children属性
通过props.children实现组件嵌套,适合布局类组件。例如:
function Card({ children }) {
return <div className="card">{children}</div>;
}
// 重用示例
<Card><h3>标题</h3></Card>
<Card><p>内容段落</p></Card>
高阶组件(HOC)模式
包装组件增强功能
通过函数接收组件并返回新组件,实现逻辑复用。例如实现加载状态:
function withLoading(Component) {
return function EnhancedComponent({ isLoading, ...props }) {
return isLoading ? <Spinner /> : <Component {...props} />;
};
}
const EnhancedButton = withLoading(Button);
自定义Hook复用逻辑
提取状态逻辑
将组件中的状态逻辑提取为可复用的Hook。例如表单处理:
function useForm(initialValues) {
const [values, setValues] = useState(initialValues);
const handleChange = (e) => {
setValues({ ...values, [e.target.name]: e.target.value });
};
return [values, handleChange];
}
// 组件内使用
const [formData, handleChange] = useForm({ username: '', password: '' });
组件组合模式
通过组件嵌套实现
将多个小组件组合成复杂组件,例如构建可复用的表单字段:
function FormField({ label, type }) {
return (
<div>
<label>{label}</label>
<input type={type} />
</div>
);
}
// 组合使用
<FormField label="用户名" type="text" />
<FormField label="密码" type="password" />
Context API共享状态
跨层级组件复用
通过Context提供全局数据,避免多层props传递。例如主题配置:
const ThemeContext = createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
// 子组件消费
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>按钮</button>;
}
注意事项
- 保持组件单一职责原则,每个组件只关注特定功能
- 合理划分组件粒度,避免过度拆分导致维护困难
- 对高频复用组件使用
React.memo优化性能 - TypeScript用户应为可复用组件定义清晰的props类型







