react如何重用组件
React 重用组件的常用方法
通过 props 传递数据和配置 将组件设计为可配置的,通过 props 接收不同参数。例如创建一个可复用的按钮组件,通过 props 控制其样式、文本和点击行为。
function Button({ color, text, onClick }) {
return (
<button style={{ backgroundColor: color }} onClick={onClick}>
{text}
</button>
);
}
// 使用
<Button color="blue" text="Submit" onClick={handleSubmit} />
使用 children 属性组合组件
通过 children 实现内容注入,允许组件包裹任意子元素。这种方式适合构建布局组件或容器组件。
function Card({ children }) {
return <div className="card">{children}</div>;
}
// 使用
<Card>
<h2>Title</h2>
<p>Content</p>
</Card>
高阶组件(HOC)模式 通过函数接收组件并返回增强后的新组件。适合跨组件共享逻辑,如认证、日志等横切关注点。

function withLogger(WrappedComponent) {
return function(props) {
console.log('Rendered:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogger(MyComponent);
自定义 Hook 共享状态逻辑 将组件中的状态逻辑提取为可重用的 Hook。适合非视觉逻辑的复用,如表单处理、数据获取等。
function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(c => c + 1);
return { count, increment };
}
// 在多个组件中使用
function ComponentA() {
const { count, increment } = useCounter(0);
// ...
}
组件组合设计 通过多个小组件组合成复杂组件。将功能拆分为更小的单元,通过组合方式复用。

function Form() {
return (
<form>
<Input label="Username" />
<Input label="Password" type="password" />
<Button>Submit</Button>
</form>
);
}
Context API 共享全局数据 通过 Context 提供全局可访问的数据,避免多层 props 传递。适合主题、用户信息等全局状态。
const ThemeContext = createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
// ...
}
渲染属性(Render Props) 通过函数 prop 动态决定渲染内容,实现行为与渲染分离。适合需要高度自定义渲染的场景。
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
// ...
return render(position);
}
// 使用
<MouseTracker render={({ x, y }) => (
<p>Mouse position: {x}, {y}</p>
)} />






