【问题标题】:Children won't render when using a layout in ReactJS在 ReactJS 中使用布局时,子项不会呈现
【发布时间】:2023-01-18 00:32:00
【问题描述】:

我在我的项目中使用 MUIv5 和 React-Router v6,我想在我的页面周围包装一个布局,但页面没有呈现,我得到的只是一个空的 div

这是我的 App 组件:

import React from "react";
import { Routes, Route } from "react-router-dom";
import { CssBaseline } from "@mui/material";

import MainLanding from './routes/MainLanding';
import StoreLanding from "./routes/StoreLanding";
import Layout from "./components/Layout";

const App = () =>{
    return(
        <>
            <CssBaseline/>
                <Routes>
                    <Route element={<Layout/>}>
                        <Route path="/" element={<MainLanding/>}/>
                        <Route path="/store" element={<StoreLanding/>}/>
                    </Route>
                </Routes>
        </>
    )
}

export default App

这是我通过道具调用孩子的布局组件:

import React from 'react';

const Layout = ({ children }) => {
    return (
        <div>
            {children}
        </div>
    )
}
export default Layout;

输出:

【问题讨论】:

标签: reactjs react-router react-router-dom


【解决方案1】:

布局组件应该渲染一个 Outlet 来让嵌套的 Route 组件被渲染到。这与使用和呈现 children 属性的包装器组件不同。

有关详细信息,请参阅Layout RoutesOutlet

import { Outlet } from 'react-router-dom';

const Layout = () => {
  return (
    <div>
      <Outlet /> // <-- nested routes rendered here!
    </div>
  )
};

为了进行比较,包装器组件用于将子组件包装在 element prop 中。例子:

<Routes>
  <Route
    path="/"
    element={(
      <Layout>
        <MainLanding />
      </Layout>
    )}
  />
  <Route
    path="/store"
    element={(
      <Layout>
        <StoreLanding />
      </Layout>
    )}
  />
</Routes>

【讨论】:

  • 这应该真正显示在 react-router 文档中
  • @Alex Ive 编辑链接到一些相关文档。谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2017-07-07
相关资源
最近更新 更多