我正在尝试找到一种方法来让我的第 3 方 Toast 组件在子组件中可用。在我的示例中,我让它与 app.js
的直接子级一起使用。 。但我不知道如何让孙子们使用它。
我有一个仓库:https://github.com/CraigInBrisbane/ReactLearning如果有帮助的话。 (从来没有做过开源的东西,所以不确定是否可以编辑)
我正在尝试使用这个组件: (https://github.com/jossmac/react-toast-notifications)
在我的 app.js 中导入包,然后加载子组件:
<Route exact path="/accounts" component={withToastManager(Accounts)} />
然后(以某种方式)我的子组件可以访问 toastManager:
const { toastManager } = this.props;
我可以通过以下方式显示 toast 通知:
toastManager.add('Login Success', {
appearance: 'success',
autoDismiss: true,
pauseOnHover: false,
});
但是,对于我的导航栏...我有一些结构。
Header 是我从 app.js 调用的组件... Header 本身不使用 Toast。但它有一个名为 NavBar 的子项,其中有一个注销按钮。当我单击“注销”时,我想显示 toast。
但它不知道 ToastManager 是什么。
我正在尝试这个:
handleLogout() {
const { toastManager } = this.props;
const {pathname} = this.props.location;
this.context.changeAuthenticated(false);
if(pathname !== "/") {
this.props.history.push("/");
}
toastManager.add('You\re now logged out', {
appearance: 'success',
autoDismiss: true,
pauseOnHover: false,
});
}
但是 toastManager 不是我可用的项目。
有没有办法让任何将使用 Toast 通知的组件了解它们?我想我需要将我的导航栏包裹在 withToastManager
中,但是我所有的 sibling 都需要引用 ToastManager。
任何指导都会很棒。
最佳答案
您应该看看react's Higher Order Component (HOC)文档,但基本上您希望单独包装每个需要注入(inject) withToastManager
prop(s) 的组件。
在您的 navbar.js
文件中,您需要从“react-toast-notifications”导入 withToastManager
,并包装导出:
import { toastManager } from 'react-toast-notifications';
...
export default withToastManager(
withRouter(Navbar)
);
这会将 toast 管理器添加为 Prop ,您可以通过 this.props.toastManager
在组件中访问它。
旁注,通常您还需要使用相同的模式来包装需要 HOC 提供的 props/功能的组件的导出,而不是应用程序中的其他位置,例如在 app.js 中的路由器中。
关于javascript - 使我的 Toast 组件可供子组件使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56783540/