简体   繁体   中英

How would you use conditional hooks inside a React.Component class

Per documentation, Hooks cannot be used inside class components. But there are ways with higher order components: How can I use React hooks in React classic `class` component? . However this answer provided does not address the case of hooks that get called on function invocation. Take this simple Toast hook from: https://jossmac.github.io/react-toast-notifications/ . I'd like to call the hook inside of a class of form:

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

   }
```

There'd be no way of calling addToast without using const { addToast } = useToasts() in the class method, which would throw error.

You can use withToastManager HOC to archive that work

Here is an example

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);

For more information you can also find here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM