简体   繁体   English

如何在 Next.js 中的路由之间使用共享组件

[英]How can I use shared components between routes in Next.js

I'm thinking of migrating from create-react-app to Next.js I need to share component between routes in Next.js I tried the Layout file example below and it worked pretty well for me but I have a special case where I need the shared component to be above the router itself.我正在考虑从 create-react-app 迁移到 Next.js 我需要在 Next.js 中的路由之间共享组件 我尝试了下面的布局文件示例,它对我来说效果很好,但我有一个特殊情况,我需要共享组件高于路由器本身。

For example, if I have a video element and want the video to still playing if I changed the route例如,如果我有一个视频元素,并且如果我改变了路线,我希望视频仍然在播放

const Layout = (props) => (
  <div>
      {props.children}
      <video width="400" controls>
        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"/>
        Your browser does not support HTML5 video.
      </video>

  </div>
)
const Home = () => (
  <Layout>
    <Link href="/about"><a>About</a></Link>
    <h1 className='title'>Welcome to Home!</h1>
  </Layout>
)
const About = () => (
  <Layout>
    <Link href="/"><a>Home</a></Link>
    <h1 className='title'>Welcome to About!</h1>
  </Layout>
)

Example from another project using create-react-app and reach-router the player component is above the router来自另一个使用 create-react-app 和reach-router 的项目的示例,播放器组件位于路由器上方

<Layout>
    <Player/>
    <Router className={'router'}>
        <Login path={Routes.login}/>
        <NotFound404 default/>
        <Home path={Routes.root}/>
        <Test path={Routes.test}/>
    </Router>
<Layout/>

The shared element will be the video tag, the problem is on every route change the video is rendered and replayed共享元素将是视频标签,问题在于每条路线更改都会渲染和重播视频

You might wanna check the docs on using pages/_app.js for that.您可能想查看有关使用pages/_app.js的文档。

Example usage is shown below:示例用法如下所示:

import Head from "next/head";

type Props = {
  pageProps: any;
  Component: React.FC;
};

const App = ({ Component, pageProps }: Props) => {
  return (
    <>
      <Head>
        // You can put whatever you want to put in your document head
      </Head>

      <YourSharedComponent />

      <Component {...pageProps} />

      <style>{`
        // styles...
      `}</style>
    </>
  );
};

App.getInitialProps = async ({ Component }) => {
  const pageProps = Component.getInitialProps && await Component.getInitialProps(ctx, loggedUser);

  return {
    pageProps,
  }
};

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM