javascript - 您将如何在 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()
,这会引发错误。
解决方案
您可以使用withToastManager
HOC 归档该工作
这是一个例子
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);
有关更多信息,您还可以在此处找到
推荐阅读
- eclipse - 如何从 Eclipse 历史记录中大量恢复所有文件编辑?
- slurm - 指定选项 `-o` 时,slurm/sbatch 不起作用
- c++ - 用于多线程、甚至驱动的状态模式实现的 C++ 基类
- amazon-web-services - AWS QuickSight 如何组合来自多个数据集的字段
- laravel - 合并多次分组的集合
- stream - 读取 SU 和 SEGY 格式的地震数据集
- python - 对另一个字典中的字典“分组依据”键值求和值
- python - get() 返回了多个 Product -- 它返回了 14
- python - 由于套接字未在 Python 中连接,因此不允许发送或接收数据的请求
- python - 如何将 str.startswith 与多个字符串一起使用?