【问题标题】:React hook inheritance反应钩子继承
【发布时间】:2020-06-18 01:53:13
【问题描述】:

我使用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 组件更改为 hooks。我想使用这个功能。但无法将Wrapper 转换为hooks 的用法。

标签: reactjs class ecmascript-6 react-hooks react-component


【解决方案1】:

你不能在类组件中使用钩子。但我会尽力提供解决方案。

鉴于您基本上希望能够从任何组件内部调用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 的代码,我们将尝试提供解决方案:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多