在Nextjs中向_app.js添加持久性组件

时间:2020-05-25 15:55:41

标签: javascript reactjs next.js

所以我在玩我的第一个Nextjs应用程序,并且在添加持久性边栏时遇到麻烦。

我在nextjs中的持久性布局上发现了Adam Wathan's article,但似乎最近使用_app.js页面添加了一个更新的模式。我去过the docs和它周围的一些github问题,但是看起来周围没有很多文档。

因此,在我的示例中,我有_app.js文件:

import '../css/tailwind.css'
import Head from 'next/head'
import Sidebar from "../components/Sidebar";

export default function App({Component, pageProps}){
  return(
    <>
      <Head />
        <Component {...pageProps} />
    </>
  )
}
import React, { useState } from "react";
import Transition from "../components/Transition";
import Link from 'next/link'

function Sidebar({ children }) {
 const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [hideSidebarMenu, setHideSidebarMenu] = useState(true);

  const openSidebar = () => {
    setIsSidebarOpen(true);
    setHideSidebarMenu(false);
  };

  const closeSidebar = () => {
    setIsSidebarOpen(false);
  };

  const hideSidebar = () => {
    setHideSidebarMenu(true);
  };

  return(
    <div>
      /*sidebar links here*/
    </div>
  )
}

export default Sidebar;

如何将侧边栏组件集成到其中?我尝试将其添加到组件和包装组件旁边,并且没有几次运气。希望我只是缺少一些简单的东西。

1 个答案:

答案 0 :(得分:1)

这很奇怪。我本来会发誓以前尝试过这种非常简单的解决方案,但是这样的事情就足够了。

此解决方案将使用侧边栏中的children道具将页面输入到您要访问的页面。

import '../css/tailwind.css'
import Head from 'next/head'
import Sidebar from "../components/Sidebar";

export default function App({Component, pageProps}){
  return(
    <>
      <Head />
      <Sidebar >
        <Component {...pageProps} />
      </Sidebar>
    </>
  )
}

此选项只会将边栏与内容一起呈现

import '../css/tailwind.css'
import Head from 'next/head'
import Sidebar from "../components/Sidebar";

export default function App({Component, pageProps}){
  return(
    <>
      <Head />
      <Sidebar />
      <Component {...pageProps} />
    </>
  )
}