【发布时间】: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})
【问题讨论】:
-
你能发布完整的代码吗?我可以知道
<ViewContainer> <Switch>{switchRoutes}</Switch> </ViewContainer>是做什么的吗? -
@Rookie007 这只是我的应用程序的其余部分,可以替换为进行测试。
来自 react-router-dom 而 switchRoutes 是所有路由的映射。
标签: reactjs material-ui react-context