react如何封装
封装组件的基本方法
在React中封装组件通常遵循单一职责原则,确保每个组件只负责一个特定功能。将UI和逻辑分离,通过props传递数据和回调函数。
const Button = ({ onClick, children }) => {
return <button onClick={onClick}>{children}</button>;
};
使用自定义Hooks封装逻辑
将可复用的状态逻辑提取到自定义Hook中,实现逻辑与UI的解耦。自定义Hook必须以"use"开头命名。
const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return { count, increment };
};
高阶组件封装
通过高阶组件(HOC)模式增强现有组件功能。HOC是一个接收组件并返回新组件的函数。
const withLoading = (Component) => {
return ({ isLoading, ...props }) => {
return isLoading ? <Spinner /> : <Component {...props} />;
};
};
复合组件模式
使用React Context和复合组件模式封装具有复杂交互的组件族,对外暴露简洁的API。
const Tabs = ({ children }) => {
const [activeTab, setActiveTab] = useState(0);
return (
<TabContext.Provider value={{ activeTab, setActiveTab }}>
{children}
</TabContext.Provider>
);
};
类型检查与默认值
使用PropTypes或TypeScript定义组件接口,明确props类型要求并设置默认值。
import PropTypes from 'prop-types';
Card.propTypes = {
title: PropTypes.string.isRequired,
size: PropTypes.oneOf(['sm', 'md', 'lg']),
};
Card.defaultProps = {
size: 'md',
};
样式封装方案
采用CSS Modules、Styled-components或Emotion等方案实现样式封装,避免全局污染。
import styles from './Button.module.css';
const Button = () => {
return <button className={styles.primary}>Submit</button>;
};
性能优化封装
使用React.memo、useMemo和useCallback优化组件性能,避免不必要的重新渲染。
const MemoizedComponent = React.memo(({ list }) => {
return <ul>{list.map(item => <li key={item.id}>{item.text}</li>)}</ul>;
});
组件文档规范
为封装组件编写清晰的文档说明,包括props定义、使用示例和注意事项。
## Button
A reusable button component.
### Props
- `variant`: 'primary' | 'secondary'
- `size`: 'small' | 'medium' | 'large'
- `onClick`: () => void







