React:不使用钩子的基于类的组件中的钩子无效

如何解决React:不使用钩子的基于类的组件中的钩子无效

我对React有一些问题。我想以类的形式创建一个组件库(我来自Java世界,我发现OOP更具可读性)。

为此,我创建了一个基类,所有组件都将从该基类继承。

import { Box,createMuiTheme,Theme } from '@material-ui/core';
import React from 'react';
import { findDOMNode } from 'react-dom';
import { MyTheme,defaultPalette } from '../MyTheme/MyTheme';
import { BoxProps } from './BoxProps';
import { MyComponentProperties,MyComponentState } from './MyComponent.types';
import { ComponentUtilities } from './ComponentUtilities';
import { EventListenerPool } from './EventListenerPool';

/**
 * Default class for create a Component with this library
 * @abstract
 */
export abstract class
  MyComponent<P extends MyComponentProperties,S extends MyComponentState>
  extends React.Component<P,S> {

  static readonly VERSION: number = 100;

  /**
   * Constant for the event : componentDidMount
   * @constant EVENT_COMPONENT_DID_MOUNT
   */
  protected static readonly EVENT_COMPONENT_DID_MOUNT = 'EVENT_COMPONENT_DID_MOUNT';
  /**
   * Constant for the event : componentWillUnmount
   * @constant EVENT_COMPONENT_WILL_UNMOUNT
   */
  protected static readonly EVENT_COMPONENT_WILL_UNMOUNT = 'EVENT_COMPONENT_WILL_UNMOUNT';
  /**
   * Constant for the event : clickOutside
   * @constant EVENT_COMPONENT_CLICK_OUTSIDE
   */
  protected static readonly EVENT_COMPONENT_CLICK_OUTSIDE = 'EVENT_COMPONENT_CLICK_OUTSIDE';

  /**
   * Listener's pool for trigger events
   * @type {Map<string,EventListenerPool>}
   */
  private readonly eventListenerPools: Map<string,EventListenerPool>;
  /**
   * Component theme
   * @property {Theme}
   */
  protected readonly theme: Theme;
  /**
   * Generic id if the property's id is missing
   * @type {string}
   */
  private genericId: string = ComponentUtilities.getNewGenericMyComponentId();
  /**
   * Root node in the DOM
   * @type {Element | null | Text} 
   */
  protected rootNode: Element | null | Text;

  /**
   * @constructor
   * @param props Properties for create the component
   */
  constructor(props: P) {
    super(props);
    this.rootNode = null;
    this.state = {} as unknown as S;
    this.eventListenerPools = new Map<string,EventListenerPool>();
    this.initComponentListeners();
    this.theme = this.createTheme();
  }

  /**
   * Get component's ID
   * @returns ID property or the generic ID
   */
  get id(): string {
    let id = this.props.id;
    if (id === undefined) {
      id = this.genericId;
    }

    return id as string;
  }

  /**
   * Get style for the component
   * @returns component style
   */
  protected get style(): React.CSSProperties | undefined {
    return this.props.style;
  }

  /**
   * Get disabled property
   * @returns true if the component is disabled
   */
  get isDisabled(): boolean | undefined {
    return this.props.disabled;
  }

  /**
   * Get component's class name
   * @returns Class name
   */
  protected get className(): string | undefined {
    return this.props.className;
  }

  /**
   * Get component's children
   * @returns children
   */
  protected get children(): React.ReactNode | undefined {
    return this.props.children;
  }

  /**
   * Create a new pool listner for specific event type
   * @param eventType Event type
   */
  protected createEventListenerPool(eventType: string): void {
    this.eventListenerPools.set(eventType,new EventListenerPool());
  }

  /**
   * Get the listener pool which is associated with the type of event
   * @param eventType Event type
   * @returns listener pool or undefined if the pool isn't created
   */
  private getEventListenerPool(
    eventType: string
  ): EventListenerPool | undefined {
    return this.eventListenerPools.get(eventType);
  }

  /**
   * Add a new listener in a listener pool
   * @param eventType Event type
   * @param listener Listener to add
   */
  protected addListenerInListenerPool(eventType: string | Array<string>,// eslint-disable-next-line @typescript-eslint/ban-types
    listener?: Function): void {
    if (listener) {
      const pools = new Array<EventListenerPool>();

      if (eventType instanceof Array) {
        eventType.forEach((event) => {
          const pool = this.getEventListenerPool(event);
          if (pool) {
            pools.push(pool);
          }
        });

      } else {
        const listenerPool = this.getEventListenerPool(eventType);
        if (listenerPool) {
          pools.push(listenerPool);
        }
      }

      pools.forEach((pool) => pool.add(listener));
    }
  }

  /**
   * Basic method for fire an event
   * @param eventType Event type key
   * @param event Event to fire
   */
  protected fireBasicEventType(eventType: string,event?: unknown): void {
    const listenerPool = this.getEventListenerPool(eventType);

    if (listenerPool) {
      listenerPool.fireEvent(event);
    }
  }

  /**
   * Initialize component listeners
   */
  protected initComponentListeners(): void {
    this.createEventListenerPool(MyComponent.EVENT_COMPONENT_DID_MOUNT);
    this.addComponentDidMountListener(this.props.onComponentDidMount);
    this.createEventListenerPool(MyComponent.EVENT_COMPONENT_WILL_UNMOUNT);
    this.addComponentWillUnmountListener(this.props.onComponentWillUnmount);
    this.createEventListenerPool(MyComponent.EVENT_COMPONENT_CLICK_OUTSIDE);
    this.addClickOutsideListener(this.props.onClickOutside);
  }

  /**
   * Add a listener when the component did mount
   * @param listener Listener
   */
  private addComponentDidMountListener(listener?: (() => void)): void {
    this.addListenerInListenerPool(MyComponent.EVENT_COMPONENT_DID_MOUNT,listener);
  }

  /**
   * Function called when component did mount.
   * Add a default listener on mousedown event for manage the click outside the component
   */
  componentDidMount(): void {
    this.rootNode = findDOMNode(this);
    document.addEventListener('mousedown',this.handleClickOutside.bind(this));
    this.fireBasicEventType(MyComponent.EVENT_COMPONENT_DID_MOUNT);
  }

  /**
   * Add a listener when the component will unmount
   * @param listener Listener
   */
  private addComponentWillUnmountListener(listener?: (() => void)): void {
    this.addListenerInListenerPool(MyComponent.EVENT_COMPONENT_WILL_UNMOUNT,listener);
  }

  /**
   * Add a listener when click outside the component
   * @param listener Listener
   */
  private addClickOutsideListener(listener?: ((event: MouseEvent) => void)): void {
    this.addListenerInListenerPool(MyComponent.EVENT_COMPONENT_CLICK_OUTSIDE,listener);
  }

  /**
   * Function called when the component will unmount
   */
  componentWillUnmount(): void {
    document.removeEventListener('mousedown',this.handleClickOutside.bind(this));
    this.fireBasicEventType(MyComponent.EVENT_COMPONENT_WILL_UNMOUNT);
  }

  /**
   * Create the theme for the component
   * @returns Theme for the component
   */
  protected createTheme(): Theme {
    return createMuiTheme(this.defaultComponentTheme());
  }

  /**
   * Get the default theme for the component
   * @returns Default theme
   */
  private defaultComponentTheme(): MyTheme {
    return defaultPalette;
  }

  /**
   * The render for the React component. Wrap the compoent's render.
   * @returns The element that will be used in the DOM
   */
  render(): JSX.Element {
    let element: JSX.Element;

    element = this.renderComponent();
    element = this.wrapElement(element);

    return element;
  }

  /**
   * The method for render compnent. Return only the component's render
   * @returns Element will be used in the DOM for the component
   */
  protected abstract renderComponent(): JSX.Element;

  /**
   * Wrap the element with a Box component
   * @param oriElement Element to wrap
   * @returns Wrapped element
   */
  protected wrapElement(oriElement: JSX.Element): JSX.Element {
    let element = oriElement;
    const { boxProps } = this.props;
    element = this.wrapWithBoxProps(element,boxProps);
    return element;
  }

  protected wrapWithBoxProps(oriElement: JSX.Element,boxProps?: BoxProps): JSX.Element {
    let element = oriElement;

    if (boxProps) {
      element = (
        <Box {...boxProps}>
          {element}
        </Box>
      );
    }

    return element;
  }

  /**
   * Handle the event when click outside the element.
   * Fire event only if the mousedown event is outside the component
   * @param event The event mousedown
   */
  protected handleClickOutside(event: MouseEvent): void {
    if (!this.childOf(event.target as Element | null)) {
      this.fireBasicEventType(MyComponent.EVENT_COMPONENT_CLICK_OUTSIDE,event);
    }
  }

  /**
   * Check if the element is in the component (in the DOM)
   * @param node Node to check
   * @returns true if the element is in the component DOM
   */
  protected childOf(node: (Node & ParentNode) | null) {
    let child = node;
    let check = false;
    while (child !== null) {
      if (child === this.rootNode) {
        check = true;
        break;
      }
      child = child.parentNode;
    }
    return check;
  }
}

然后,我有一个基本组件来显示警报。

import { Alert,AlertTitle } from '@material-ui/lab';
import React from 'react';
import { MyComponent } from '../MyComponent/MyComponent';
import { MyAlertProperties,MyAlertState } from './MyAlert.types';

/**
 * An alert displays a short,important message in a way that attracts the user's attention without interrupting the user's task.
 * @extends MyComponent
 */
export class MyAlert extends MyComponent<MyAlertProperties,MyAlertState> {

  static readonly VERSION: number = 100;

  /**
   * @override
   */
  protected renderComponent(): JSX.Element {
    const { elevation,severity,variant } = this.props;
    const element = (
      <Alert
        elevation={elevation}
        variant={variant}
        severity={severity}
      >
        {this.getRenderTitle()}
        {this.children}
      </Alert>
    );

    return element;
  }

  /**
   * Render the alert's title
   * @returns Alert's title element
   */
  private getRenderTitle(): JSX.Element {
    const { title } = this.props;
    let element = undefined as unknown as JSX.Element;
    if (title) {
      element = (<AlertTitle>{title}</AlertTitle>);
    }

    return element;
  }

}

我已经使用rollupjs构建了自己的库,并且可以通过故事书很好地工作。

然后,我想将我的库与React应用程序中的npm依赖项相关联,该应用程序是我之前通过“ create-react-app”通过打字稿模板创建的。在App.tsx中,我调用了我的组件,但是在我的组件中未使用任何错误消息时,收到以下错误消息“ Invalid hook call”。

import React from 'react';
import { MyAlert } from 'myreactlib/build';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <MyAlert>Alert</MyAlert>
  </React.StrictMode>,document.getElementById('root')
);

// If you want your app to work offline and load faster,you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();

如果我使用简单的div,则App.tsx可以正常工作。

我不知道我的问题可能来自哪里。我不使用钩子。我知道基于类的组件中禁止使用它。 有关信息,我的应用程序上的react版本似乎不错:

  • react@16.13.1
  • react-dom@16.13.1

如果有人有想法? 谢谢

解决方法

您可能在您的应用程序中重复了React实例,这可能会生成此误导性错误消息。参见https://github.com/facebook/react/issues/13991

确保React是一个对等依赖项,并且没有将其捆绑在库中,也没有通过npm link使用库。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res