![](/img/trans.png)
[英]react-router-dom and typescript not displaying the components
[英]React navbar renders components separately with react-router-dom
我正在使用 react router dom 來呈現帶有 react 和 tailwindcss 的網站。 單擊時導航欄會刷新並在沒有其他組件的情況下單獨呈現組件。 這不是我想要的。
我希望組件按照我的 App.js 文件中的結構在單個頁面中呈現
我試過使用普通的 hrefs,現在從 react-router-dom 鏈接,但我仍然得到相同的結果
應用程序.js
const App = () => {
return (
<div className="max-w-[1440px] mx-auto bg-page overflow-hidden relative">
<Header />
<Routes>
<Route path="/" element={<Banner />} />
<Route path="/home" element={<Banner />} />
<Route path="/about" element={<About />} />
<Route path="/hero" element={<Hero />} />
<Route path="/featured" element={<Featured />} />
<Route path="/gallery" element={<GallerySection />} />
<Route path="/testimonies" element={<Testimony />} />
<Route path="/join" element={<Join />} />
<Route path="/footer" element={<Footer />} />
<Route path="/copy" element={<Copyright />} />
</Routes>
</div>
);
};
export default App;
索引.js
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>
);
導航欄.js
const Nav = () => {
return (
<nav className="hidden lg:flex">
<ul className="flex gap-x-8 text-white">
{["home", "about", "featured", "gallery", "testimonies", "join"].map(
(item) => {
return (
<li key={`link-${item}`}>
<Link to={`/${item}`} className="capitalize">
{item}
</Link>
</li>
);
}
)}
</ul>
</nav>
);
};
export default Nav;
如果有任何幫助,我將不勝感激
您需要使用主題標簽而不是不同的路線。
所以你必須只使用一個索引路由
<Route path="/" element={<IndexPage />} />
並在IndexPage
組件中一一渲染 section 組件
const IndexPage = () => (
<>
<Banner />
...
</>
)
然后添加到每個部分組件包裝器id
屬性
const Banner = () => (
<div id="banner">
...content...
</div>
)
並在 Nav 組件中使用主題標簽鏈接:
<Link to={`#${item}`} className="capitalize">
{item}
</Link>
鏈接看起來像domain.com/#banner
,如果使用打開它,那么瀏覽器將向下滾動到具有id
的特定元素
我還建議添加一些 css 以使滾動平滑:
html {
scroll-behavior: smooth;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.