面试题答案
一键面试React高阶组件(HOC)解释
高阶组件(HOC)是 React 中用于复用组件逻辑的一种高级技巧。它本身不是 React API 的一部分,而是一种基于 React 的组合特性形成的设计模式。HOC 是一个函数,它接受一个组件作为参数,并返回一个新的组件。新组件会包含传入组件的所有功能,同时还可以添加额外的功能,如状态管理、副作用操作等,实现逻辑的复用。
使用高阶组件添加日志记录功能示例
- 创建高阶组件
import React from 'react';
// 高阶组件,用于添加日志记录功能
const withLogging = (WrappedComponent) => {
return (props) => {
console.log(`Rendering ${WrappedComponent.name}`);
return <WrappedComponent {...props} />;
};
};
export default withLogging;
- 在其他组件中使用高阶组件
import React from'react';
import withLogging from './withLogging';
// 普通组件
const MyComponent = (props) => {
return <div>{props.message}</div>;
};
// 使用高阶组件包装 MyComponent
const LoggedMyComponent = withLogging(MyComponent);
const App = () => {
return (
<div>
<LoggedMyComponent message="Hello, HOC!" />
</div>
);
};
export default App;
在上述代码中,withLogging
是一个高阶组件,它接受一个组件 WrappedComponent
作为参数。返回的新组件在渲染 WrappedComponent
之前,会在控制台打印一条日志信息。然后,通过 withLogging(MyComponent)
将 MyComponent
包装成 LoggedMyComponent
,LoggedMyComponent
就拥有了日志记录功能。在 App
组件中使用 LoggedMyComponent
时,每次渲染该组件都会在控制台看到相应的日志。