React面试题:React高阶组件

发布时间:2023年12月18日

回答思路:复用组件逻辑

高阶组件(HOC:Higher-Order Components)是React中用于复用组件逻辑的一种,和高阶函数(参数为函数,返回值也是函数)很相似,以组件作为参数,返回一个新的组件,它本身不属于React API,它是一种基于React组合特性的设计模式

import React, { Component } from 'react';

// withAuth 高阶组件
function withAuth(WrappedComponent) {
  return class extends Component {
    state = {
      isAuthenticated: false,
    };

    componentDidMount() {
      // 模拟身份验证逻辑
      const isAuthenticated = checkUserAuthenticated(); // 假设有一个函数用于检查用户是否已经进行身份验证
      this.setState({ isAuthenticated });
    }

    render() {
      const { isAuthenticated } = this.state;

      // 根据身份验证状态渲染原始组件或其他内容
      if (isAuthenticated) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <div>请先登录</div>;
      }
    }
  };
}

// 原始组件
class MyComponent extends Component {
  render() {
    return <div>经过身份验证的内容</div>;
  }
}

// 使用 withAuth 高阶组件包装 MyComponent
const AuthenticatedComponent = withAuth(MyComponent);

然后直接使用<AuthenticatedComponent? />这个组件即可

缺点:prop覆盖问题

// 定义一个简单的高阶组件
function withPrefix(WrappedComponent) {
  return function WithPrefix(props) {
    return <WrappedComponent prefix="HOC" {...props} />;
  };
}

// 原始组件
function MyComponent(props) {
  return <div>{props.prefix} - {props.name}</div>;
}

// 使用高阶组件包装原始组件
const EnhancedComponent = withPrefix(MyComponent);

// 渲染组件
ReactDOM.render(<EnhancedComponent prefix="Original" name="Component" />, document.getElementById('root'));

渲染结果为:?"HOC - Component",“HOC”覆盖了“Original”

文章来源:https://blog.csdn.net/laowang357/article/details/134936943
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。