我好奇的不是如何使用代码,而是在哪里使用代码的标准。
我有三个主要组件来构建我的项目。
index.tsx
import App from "App";
import ReactDOM from "react-dom/client";
import "./index.css";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
// <React.StrictMode>
<App />
// </React.StrictMode>
);
然后是App.js
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import Root from "./Root";
import Home from "./pages/Home/Home";
import { Location } from "./pages/Location/components/Location";
import { Recruit } from "./pages/Recruit/components/Recruit";
import { Service } from "./pages/Service/components/Service";
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
errorElement: "Not Found",
children: [
{
index: true,
path: "/",
element: <Home />,
},
{
path: "/service",
element: <Service />,
},
{
path: "/recruit",
element: <Recruit />,
},
{
path: "/location",
element: <Location />,
},
],
},
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;
最后,Root.tsx 是
import { Footer } from "Layout/Footer";
import { Header } from "Layout/Header";
import { Outlet, ScrollRestoration } from "react-router-dom";
export default function Root() {
return (
<div>
<Header></Header>
<ScrollRestoration />
<Outlet></Outlet>
<Footer></Footer>
</div>
);
}
为了将滚动重新调整到顶部,我在index.tsx文件中使用了库中的
<ScrollRestoration />
,因为在互联网上的大多数帖子和文章中,他们在index.tsx文件中使用它。
但是,在我的项目中,它不起作用。我的网页屏幕黑屏,没有任何内容。
所以,我在 App.js 文件中使用了
<ScrollRestoration />
,但即使我将文件扩展名从 js 更改为 ts 或 tsx,它也不起作用。
最后,我在 Root.tsx 中将
<ScrollRestoration />
与 <Outlet>
一起使用。效果很好。
所以,我解决了我的问题,但我不明白为什么?
使用它的位置或文件是否有标准?如果可以的话,标准是什么?
直接来自 ScrollRestoration 文档:
重要 此功能仅在使用数据路由器时才有效,请参阅选择路由器
您应该只渲染其中之一,建议您渲染它 在您应用程序的根路径中:
import { ScrollRestoration } from "react-router-dom"; function RootRouteComponent() { return ( <div> {/* ... */} <ScrollRestoration /> </div> ); }
ScrollRestoration
在您的index.tsx
或App
组件中不起作用,因为您将其渲染在数据路由器之外,即在RouterProvider
之外。
当您将其移动到根
Root
布局路由组件内部RouterProvider
时,它就起作用了。