我对 React router dom v6 有疑问
I have a question about React router dom v6
以下代码在 React 路由器中不起作用 dom v6.
<Route path='/study-board' element={<StudyBoard />}>
<Route path=':id' element={<StudyBoardDetail />} />
</Route>
但下面的代码有效。
<Route path='/study-board/:id' element={<StudyBoardDetail />} />
能告诉我是什么原因吗?
您必须使用 <outlet/>
来访问嵌套路由
演示代码
import { Routes, Route, Outlet } from "react-router-dom";
function App() {
return (
<Routes>
<Route path="invoices" element={<Invoices />}>
<Route path=":invoiceId" element={<Invoice />} />
<Route path="sent" element={<SentInvoices />} />
</Route>
</Routes>
);
}
function Invoices() {
return (
<div>
<h1>Invoices</h1>
<Outlet />
</div>
);
}
function Invoice() {
let { invoiceId } = useParams();
return <h1>Invoice {invoiceId}</h1>;
}
function SentInvoices() {
return <h1>Sent Invoices</h1>;
}
你不需要传递父元素
<Route path='study-board'>
<Route path=':id' element={<StudyBoardDetail />} />
</Route>
以下代码在 React 路由器中不起作用 dom v6.
<Route path='/study-board' element={<StudyBoard />}>
<Route path=':id' element={<StudyBoardDetail />} />
</Route>
但下面的代码有效。
<Route path='/study-board/:id' element={<StudyBoardDetail />} />
能告诉我是什么原因吗?
您必须使用 <outlet/>
来访问嵌套路由
演示代码
import { Routes, Route, Outlet } from "react-router-dom";
function App() {
return (
<Routes>
<Route path="invoices" element={<Invoices />}>
<Route path=":invoiceId" element={<Invoice />} />
<Route path="sent" element={<SentInvoices />} />
</Route>
</Routes>
);
}
function Invoices() {
return (
<div>
<h1>Invoices</h1>
<Outlet />
</div>
);
}
function Invoice() {
let { invoiceId } = useParams();
return <h1>Invoice {invoiceId}</h1>;
}
function SentInvoices() {
return <h1>Sent Invoices</h1>;
}
你不需要传递父元素
<Route path='study-board'>
<Route path=':id' element={<StudyBoardDetail />} />
</Route>