[英]Nested pages not loading static files using HOC
By using NextJS I have encountered a problem with the static export command next build && next export
. 通过使用NextJS,我遇到了静态导出命令
next build && next export
。
I have added the HOC - Layout.js
to wrap pages with Navbar and Footer. 我添加了HOC -
Layout.js
来使用Navbar和Footer包装页面。 Also I have shallow Pages /pages/*.js
and nested pages /pages/products/*.js
. 我还有浅页
/pages/*.js
和嵌套页面/pages/products/*.js
。
My problem is that Images in the Navbar and Footer are only loaded on the shallow pages, but navigating to /pages/products/test.js
breaks the images and they do not display. 我的问题是导航
/pages/products/test.js
和页脚中的图像仅加载在浅页上,但导航到/pages/products/test.js
会破坏图像并且不会显示。
This is only happening when exporting and serving static HTML. 这仅在导出和提供静态HTML时发生。 While developing with
npm run dev
all images are loaded correctly. 使用
npm run dev
所有图像都正确加载。
components/Layout.js 组件/ Layout.js
const withLayout = Content => {
return () => (
<Container>
<Navbar active={Content.displayName} />
<Content />
<Footer />
</Container>
);
};
export default withLayout;
pages/index.js 页/ index.js
// IMAGES WILL LOAD HERE (i.e. Logo in Navbar)
const Home = () => {
render() {
return (
<p>Test</p>
);
}
}
Home.displayName = "Home";
export default withLayout(Home);
pages/products/test.js 页/产品/ test.js
// IMAGES SET IN Layout.js WILL NOT BE LOADED
// test.jpg WILL BE LOADED
const Test = () => {
render() {
return (
<img src={"../../static/test.jpg"} />
);
}
}
Home.displayName = "Home";
export default withLayout(Test);
I solved this by creating & overwriting the file ./pages/_app.js
. 我通过创建和覆盖文件
./pages/_app.js
解决了这个问题。 The Layout it now living there and will not be rerendered on a redirect. 它现在居住在那里的布局,不会在重定向上重新渲染。
import React from "react";
import App, { Container } from "next/app";
import Navbar from "../components/Navbar";
import Footer from "../components/Footer";
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps };
}
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<Navbar active={Component.displayName} />
<Component {...pageProps} />
<Footer />
<style jsx global>{`
html,
body,
#__next {
height: 100%;
width: 100%;
margin: 0;
font-family: "Catamaran", sans-serif;
overflow-x: hidden;
}
body {
position: relative;
}
`}</style>
</Container>
);
}
}
export default MyApp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.