Является ли наличие глобального состояния [callable, setCallable] хорошей конструкцией для того, чтобы страницы прослушивали события Layout.
Пример:
Мы можем иметь кнопку Print в AppBar макета MyLayout.
Тогда каждая страница вызывает setCallable({ print: () => alert(‘print me’) }).
/* _app.tsx */
import "../styles/globals.css";
import type { AppProps } from "next/app";
import MyLayout from "../components/MyLayout";
import { useState } from "react";
function MyApp({ Component, pageProps }: AppProps) {
const [callable, setCallable] = useState();
return (
<MyLayout callable={callable}>
<Component {...pageProps} setCallable={setCallable} />
</MyLayout>
);
}
export default MyApp;
/* MyLayout.tsx */
export default function MyLayout({ children, callable }) {
return (
<>
<AppBar position="fixed" open={open}>
<Toolbar>
{callable?.print && (
<IconButton onClick={callable.print}>
<Print />
</IconButton>
)}
{/*Other buttons to call other callbacks can be added here*/}
</Toolbar>
</AppBar>
<main>{children}</main>
</>
);
}
/* MyPage.tsx */
export default function MyPage(props: any) {
useEffect(() => {
props.setCallable?.({
print: () => alert("print the current page"),
/* Other callbacks can be added here */
});
}, []);
}