首页 > 解决方案 > 您将如何在 React.Component 类中使用条件挂钩

问题描述

根据文档,Hooks 不能在类组件中使用。但是有一些方法可以使用高阶组件:如何在 React 经典 `class` 组件中使用 React 钩子?. 但是,提供的此答案并未解决在函数调用时调用挂钩的情况。从https://jossmac.github.io/react-toast-notifications/获取这个简单的 Toast 钩子。我想在一类表单中调用钩子:

```
    class MyClass extends React.Component {
        
        onTapButton = () => {
               
            if(conditionTrue){
                addToast('hello world', {
                     appearance: 'error',
                     autoDismiss: true,
                })
            } 
        }
        
        render(){ ... }

   }
```

addToast没有在类方法中使用就无法调用const { addToast } = useToasts(),这会引发错误。

标签: javascriptreactjsreact-hooks

解决方案


您可以使用withToastManagerHOC 归档该工作

这是一个例子

import React, { Component } from 'react';
import { withToastManager } from 'react-toast-notifications';

class ConnectivityListener extends Component {
  state = { isOnline: window ? window.navigator.onLine : false };

  // NOTE: add/remove event listeners omitted for brevity

  onlineCallback = () => {
    this.props.toastManager.remove(this.offlineToastId);
    this.offlineToastId = null;
  };
  offlineCallback = id => {
    this.offlineToastId = id;
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    const { isOnline } = this.state;

    if (prevState.isOnline !== isOnline) {
      return { isOnline };
    }

    return null;
  }
  componentDidUpdate(props, state, snapshot) {
    if (!snapshot) return;

    const { toastManager } = props;
    const { isOnline } = snapshot;

    const content = (
      <div>
        <strong>{isOnline ? 'Online' : "Offline"}</strong>
        <div>
          {isOnline
            ? 'Editing is available again'
            : 'Changes you make may not be saved'}
        </div>
      </div>
    );

    const callback = isOnline
      ? this.onlineCallback
      : this.offlineCallback;

    toastManager.add(content, {
      appearance: 'info',
      autoDismiss: isOnline,
    }, callback);
  }
  render() {
    return null;
  }
}

export default withToastManager(ConnectivityListener);

有关更多信息,您还可以在此处找到


推荐阅读