侧边栏壁纸
  • 累计撰写 47 篇文章
  • 累计创建 2 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

React:高阶组件HOC

高阶组件(Higher Order Component,HOC)是 React 的一种设计模式,用于增强现有组件的功能。
一个高阶组件就是一个函数,这个函数的输入为组件,输出为另一新组件。

  1. 代理式高阶组件

    高阶组件和被包裹组件有各自的生命周期
    可对原组件的 props 进行增强或者删减

// 为原组件WrappedComponent增加新的属性newProps
function addNewProps(WrappedComponent, newProps) {
    return class WrappingComponent extends React.Component {
        render(){
            return <WrappedComponent {...this.props} {...newProps}>
        }
    }
}
  1. 继承式高阶组件

    只有一个生命周期
    可以对原组件的 props 进行增强或者删减

function withAuth(WrappedComponent, newProps) {
    return class WrappingComponent extends WrappedComponent {
        render(){
            if (this.props.loggedIn) {
                this.props = {...this.props, ...newProps}
                return super.render();
            } else {
                return null;
            }
        }
    }
}
  1. 函数式子组件

    父组件必须有子组件
    子组件必须为函数

// 定义组件
class AddUserProp extends React.Component {
    render(){
        const user = 'mock user';
        return this.props.children(user);
    }
}

// 使用该组件
<AddUserProp>
{(user)=><div>user</div>}
</AddUserProp>
应用场景
  1. 权限控制:在渲染前校验用户权限,决定是否渲染组件。
  2. 数据注入:从外部数据源(如 Redux)获取数据,并通过 props 注入给组件。
  3. 性能监控:包裹组件的生命周期,进行统一的埋点或性能测量

0

评论区