反应挂钩继承

React hook inheritance

我正在使用 Wrapper 函数作为 class 的多重继承。 Wrapper 函数:

const Wrapper = (SuperClass) => class extends SuperClass {
  createNotification = (type, message, className = 'filled') => {
    switch (type) {
      case 'success':
        NotificationManager.primary(
          message,
          'Primary Notification',
          5000,
          null,
          null,
          className,
        );
        break;
    ...
    default:
        NotificationManager.info('Info message');
        break;
    }
};

并像这样使用它:

class Detail extends Wrapper(Component) {
 someFunction = () => {
  this.createNotification('success', 'Saved!');
 }
 render() {
   ...
 }
}

我的问题是如何在 hook 组件上使用它。有什么想法吗?

您不能在 class 组件内使用挂钩。但我会尽力提供解决方案。

考虑到您基本上希望能够从任何组件内部调用 createNotification,如果我们查看您的代码,我们实际上可以通过使用一个简单的实用函数来实现这一点。

你的 createNotification 函数只调用一个 NotificationManager,我相信它对你的代码是全局可用的(我没有看到你的代码的其余部分,但我想你只是导入它并使用它).

所以基本上我们可以在一个简单的函数中执行此操作,导出此函数,并在需要时随时使用它:

import NotificationManager from 'somewhere';

module.exports.createNotification = (type, message, className = 'filled') => {
    switch (type) {
      case 'success':
        NotificationManager.primary(
          message,
          'Primary Notification',
          5000,
          null,
          null,
          className,
        );
        break;
    ...
    default:
        NotificationManager.info('Info message');
        break;
    }

// import it and use it inside any component without introducing inheritance

import { createNotification } from 'somewhere-else'

// use it !

如果它不起作用,请提供您的 NotificationManager 代码,我们将尝试提供解决方案:)