我正在学习用于 Web 开发的 Next.js,我遇到了 commerce ,用 Next.js 编写的电子商务网站样板。当我浏览代码时,我发现了 Sidebar
component它使用 React Aria用于创建叠加层。
我想在自己的项目中使用这部分,所以写了一个Overlay
也使用 OverlayContainer
的组件零件。
import { useRef } from 'react';
import {
useOverlay,
useModal,
OverlayContainer
} from '@react-aria/overlays';
const Overlay = ({ className, children, open = false, onClose }) => {
const ref = useRef(null);
const { modalProps } = useModal();
let { overlayProps } = useOverlay({ onClose: onClose, open: open, isDismissable: true }, ref);
return (
<OverlayContainer>
<div
{...overlayProps}
{...modalProps}
ref={ref}
>
{children}
</div>
</OverlayContainer>
);
};
export default Overlay;
这个组件被加载到我的 Layout 组件中,就像在 commerce project 中一样。 .但是,当我尝试加载索引页面时,它给了我以下错误:
Server Error ReferenceError: document is not defined This error happened while generating the page. Any console logs will be displayed in the terminal window. Source pages/_document.tsx (90:33) @ Function.getInitialProps 88 | } 89 | > 90 | const { html, head } = await ctx.renderPage({ enhanceApp }) | ^ 91 | const styles = [...flush()] 92 | return { html, head, styles } 93 | }
当我删除
OverlayContainer
组件,它加载一切正常。我尝试更新我的依赖项,将更多代码与 Github 存储库进行比较,但到目前为止没有发现任何东西。这里有什么问题?我该如何解决?我正在使用带有 React 17.0.1 的 Next 10。
最佳答案
您可以做的解决方法是 isBrowser
这对于 NextJS 应用程序来说相当普遍。const isBrowser = typeof window !== "undefined";
使用它有条件地渲染您的 OverlayContainer
.
import { useRef } from "react";
import { useOverlay, useModal, OverlayContainer } from "@react-aria/overlays";
/**
* Utility to detect if you're on the server, or in the browser.
*/
const isBrowser = typeof window !== "undefined";
const Overlay = ({ className, children, open = false, onClose }) => {
const ref = useRef(null);
const { modalProps } = useModal();
let { overlayProps } = useOverlay(
{ onClose: onClose, open: open, isDismissable: true },
ref
);
return isBrowser ? (
<OverlayContainer>
<div {...overlayProps} {...modalProps} ref={ref}>
{children}
</div>
</OverlayContainer>
) : null;
};
export default Overlay;
关于javascript - 使用 React Aria 覆盖时的 ReferenceError : document is not defined in Next. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64614006/