面试题答案
一键面试原理
高阶组件(HOC)是一个函数,它接受一个组件并返回一个新的组件。在封装生命周期逻辑时,为了确保原始组件接收的props能正确传递和更新,需要在新组件中透传props给原始组件。同时,高阶组件通过包裹原始组件,可以在不修改原始组件代码的情况下,对其生命周期进行扩展。
实现思路
- 创建一个高阶组件函数,该函数接收原始组件作为参数。
- 在高阶组件函数内部,返回一个新的组件,这个新组件会在其生命周期(如
componentDidUpdate
)中执行需要封装的逻辑。 - 在新组件的
render
方法中,将接收到的所有props透传给原始组件。
关键代码片段
import React from 'react';
// 高阶组件函数
const withComponentDidUpdateLogic = (WrappedComponent) => {
return class extends React.Component {
componentDidUpdate(prevProps) {
// 在此处添加需要封装的逻辑,例如比较props
if (this.props.someProp!== prevProps.someProp) {
console.log('someProp has changed');
}
}
render() {
// 透传props给原始组件
return <WrappedComponent {...this.props} />;
}
};
};
// 原始组件
const MyComponent = (props) => {
return <div>{props.text}</div>;
};
// 使用高阶组件封装原始组件
const EnhancedComponent = withComponentDidUpdateLogic(MyComponent);
export default EnhancedComponent;