react如何重用组件
重用组件的核心方法
通过Props传递数据
父组件通过Props向子组件传递数据或函数,子组件接收后实现动态渲染。例如:
// 父组件
<Button text="Click Me" onClick={handleClick} />
// 子组件
const Button = ({ text, onClick }) => (
<button onClick={onClick}>{text}</button>
);
组合组件(Children)
利用props.children实现容器组件与内容的解耦:
<Card>
<h2>Title</h2>
<p>Content</p>
</Card>
// Card组件实现
const Card = ({ children }) => (
<div className="card">{children}</div>
);
高阶组件(HOC)模式
通过函数包装现有组件,扩展其功能:

const withLogger = (WrappedComponent) => {
return (props) => {
console.log('Rendered:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
};
const EnhancedButton = withLogger(Button);
自定义Hook复用逻辑
将组件逻辑提取为可复用的Hook:
const useToggle = (initialState = false) => {
const [state, setState] = useState(initialState);
const toggle = () => setState(!state);
return [state, toggle];
};
// 在多个组件中使用
const [isOn, toggleIsOn] = useToggle();
组件继承与复合
避免继承,优先组合
React官方推荐组合而非继承。通过组件嵌套或Props组合实现功能复用:

// 通过特定Props组合功能
<Modal
header={<CustomHeader />}
body={<DataTable />}
footer={<SaveCancelButtons />}
/>
Context跨层级复用
通过Context API共享全局状态或配置:
const ThemeContext = createContext('light');
// 提供者
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
// 消费者
const ThemedButton = () => {
const theme = useContext(ThemeContext);
return <button className={theme}>Button</button>;
};
渲染属性(Render Props)
通过函数Prop动态决定渲染内容:
<MouseTracker
render={(position) => (
<p>Current position: {position.x}, {position.y}</p>
)}
/>
// 实现
class MouseTracker extends React.Component {
state = { x: 0, y: 0 };
// ...跟踪鼠标逻辑
render() {
return this.props.render(this.state);
}
}
原子化设计模式
将组件拆分为最小可复用单元(如Button、Icon、Input),通过Storybook等工具维护组件库,实现跨项目复用。






