react函数组件如何混合
混合 React 函数组件的方法
在 React 中,函数组件的混合通常指的是组合多个功能或逻辑到单个组件中,而不使用类组件的继承模式。以下是几种常见的实现方式:
自定义 Hooks
自定义 Hooks 是复用逻辑的主要方式。将共享逻辑提取到自定义 Hook 中,多个组件可以调用同一个 Hook 实现功能混合。例如:

function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue(!value);
return [value, toggle];
}
function ComponentA() {
const [isOn, toggle] = useToggle();
return <button onClick={toggle}>{isOn ? 'ON' : 'OFF'}</button>;
}
高阶组件(HOC)
通过函数包裹组件实现逻辑复用。高阶组件接收一个组件并返回增强后的新组件:

function withLogger(WrappedComponent) {
return function(props) {
console.log('Rendered:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogger(ComponentA);
组合模式
通过组件嵌套和 props 传递实现功能组合。将子组件作为 props 或 children 传递给父组件:
function Parent({ children }) {
return <div className="parent">{children}</div>;
}
function App() {
return (
<Parent>
<ComponentA />
<ComponentB />
</Parent>
);
}
Context API 共享状态
使用 React.createContext 跨组件共享状态,避免逐层传递 props:
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <Button />;
}
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>Submit</button>;
}
选择策略
- 简单逻辑复用:优先使用自定义 Hooks。
- 横切关注点(如日志、权限):考虑高阶组件。
- UI 层级组合:直接使用组件嵌套。
- 深层状态共享:采用 Context API。
通过以上方法,可以灵活地混合函数组件的功能,同时保持代码的可维护性和可测试性。






