Reactjs 反应钩子遗传

Reactjs 反应钩子遗传,reactjs,class,ecmascript-6,react-hooks,react-component,Reactjs,Class,Ecmascript 6,React Hooks,React Component,我正在使用包装器函数作为类的多重继承包装器函数: const Wrapper = (SuperClass) => class extends SuperClass { createNotification = (type, message, className = 'filled') => { switch (type) { case 'success': NotificationManager.primary( messa

我正在使用
包装器
函数作为
的多重继承<代码>包装器函数:

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
组件上使用它。有什么想法吗?

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

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

您不能在类组件上使用挂钩。只有功能性组件。我现在正在将我的
组件更改为
挂钩
。我想用这个函数。但无法将
包装器
转换为
挂钩
的用法。