【问题标题】:Next JS, React have child component tell parent what to render下一个 JS,React 让子组件告诉父组件要渲染什么
【发布时间】:2022-03-15 07:37:55
【问题描述】:

我是 NextJS 和 React 的新手,想创建一些动态路由。我有一个父页面正在调用显示一些导航的子组件。

在我的父组件中,我有一个包含标题和右侧边栏的布局,它们将显示在每个页面上,但根据在我的导航组件中单击的链接,正文内容会发生变化。

我的父组件:

import React from 'react';

import { Header } from './Header;
import { SubNav } from './SubNav;
import { Sidebar } from './Sidebar;

export const AboutPage = () => {
  return (
    <>
      <Header />
      <SubNav />

      <div className="content">
        >>>I want to do something like this <<<
        {section === history && <History />}
        {section === contact && <Contact />}
          .....
      </div>

      <Sidebar />
    </>
  );
};

在我的子导航组件中,我正在映射一些数据,其中包含我在数组中定义的每个不同部分的“值”。

<NavButtons
  onClick={() => {
    const path = AppRoute.ABOUT.replace(':section', 'value');
    router.push(path, path, { shallow: true });
  }}
/>

页面路由正确,每次单击不同的导航按钮时,该部分的值都会发生变化,但我无法在父组件中更改内容,我尝试在父组件中创建一个函数,该函数将获得来自子级的值,以便我可以使用它来定义父级中的部分,但它最终会创建一个无限循环。对如何让两者一起工作感到困惑。

【问题讨论】:

  • 使用状态库。像 redux (有点矫枉过正)。可能是zustand

标签: reactjs routes next.js


【解决方案1】:

您可以使用useRouter Hook 检测路径名。 然后,您可以在 switch case 语句中检查用户所在的站点并渲染路由的组件。

import { useRouter } from next/router

组件内部

const router = useRouter();

返回组件的函数

function renderSidebar(pathname){
switch(pathname){
...
}

渲染函数内部

{ renderSidebar(router.pathname) }

在 NextJS 文档中查看更多用法 https://nextjs.org/docs/api-reference/next/router

【讨论】:

    【解决方案2】:
            import React from 'react';
            import {useState} from 'react';
            import { Header } from './Header';
            import { SubNav } from './SubNav';
            import { Sidebar } from './Sidebar';
            
            export const AboutPage = () => {
                const [section,setSection] = useState()
                sectionHandler = (section) => {
                 setSection(section)
                }
              return (
                <>
                  <Header />
                  <SubNav />
            
                  <div className="content">
                    >>>I want to do something like this <<<
                    {section === history && <History />}
                    {section === contact && <Contact />}
                      .....
                  </div>
            
                  <Sidebar />
                </>
              );
            };
        
    

    在你的孩子比赛中

         <NavButtons
          onClick={() => {
            const path = AppRoute.ABOUT.replace(':section', 'value');
            props.sectionHandler(section)
            router.push(path, path, { shallow: true });
          }}
         />
    

    不要忘记将 sectionhandler 从父组件传递给子组件

    【讨论】:

    • 我最终用 {useState} 实现了这个并且效果很好,谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2018-01-26
    • 2020-03-22
    • 2018-07-04
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多