【问题标题】:how to make snackbar a global component withContext如何使用Context使snackbar成为全局组件
【发布时间】:2021-03-23 04:17:43
【问题描述】:

我正在尝试使用一个可以从应用程序的任何页面显示(设置为 true)的 open 和 message 道具的快餐栏组件。

据我了解,我应该使用上下文。但我不太确定从哪里开始。

这是我目前所拥有的

我想在父组件的最高层有snackbar

import { createContext } from 'react';

export const SnackbarContext = createContext({});
 const [snack, setSnack] = useState({
    message: '',
    color: '',
    open: false,
  });
<SnackbarContext.Provider value={{ snack, setSnack }}>
  <Snackbar open={snack.open}>
    <Alert>
      {snack.message}
    </Alert>
  </Snackbar>
  <ViewContainer>
    <Switch>{switchRoutes}</Switch>
  </ViewContainer>
</SnackbarContext.Provider>

并且能够从任何子组件调用它

import { SnackbarContext } from 'SnackbarContext';

const { snack, setSnack } = useContext(SnackbarContext);

然后把道具改成这样的snackbar

setSnack({ message: 'hello', open: true})

【问题讨论】:

  • 你能发布完整的代码吗?我可以知道&lt;ViewContainer&gt; &lt;Switch&gt;{switchRoutes}&lt;/Switch&gt; &lt;/ViewContainer&gt; 是做什么的吗?
  • @Rookie007 这只是我的应用程序的其余部分,可以替换为
    进行测试。 来自 react-router-dom 而 switchRoutes 是所有路由的映射。

标签: reactjs material-ui react-context


【解决方案1】:

这个解决方案确实有效,我只是打错了

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 2020-06-01
    • 2020-06-04
    • 2018-06-21
    • 2021-02-21
    • 2018-06-22
    • 2016-11-06
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多