4 回答

TA貢獻1786條經驗 獲得超11個贊
<Navbar />
需要檢查 window.location 并渲染為空
請參閱https://reactrouter.com/web/api/Hooks/uselocation
或者創建一個新組件來執行檢查并將其呈現為子組件
<MayRenderNav><Navbar /></MayRenderNav>

TA貢獻1794條經驗 獲得超7個贊
要在 uke 答案上添加更多上下文,您可以使用導航欄中的 useLocation 鉤子并執行以下操作
// All the routes you want to exclude
const withouSidebarRoutes = ["/about"];
function Navbar() {
const {pathname} = useLocation();
// Validates if the current pathname includes one the routes you want to hide the sidebar is present on the current url
// If that's true render null instead of the sidebar
if (withouSidebarRoutes.some((item) => pathname.includes(item))) return null;
return (
//your navbar code.
)
}
include 很有用,因為如果您有類似的嵌套路由,about/1它也會排除該路由,如果您只想排除 about 頁面而不是嵌套頁面,請使用簡單的 equal 。
withouSidebarRoutes.some((item) => pathname === item)
檢查 hooks api 參考以了解 useLocation 可以做什么: https: //reactrouter.com/web/api/Hooks/uselocation
另外,我還有一個工作沙箱,其中一個側邊欄會在您位于“關于”部分時隱藏起來。 https://codesandbox.io/s/cranky-lewin-p8ozv

TA貢獻1805條經驗 獲得超10個贊
您的代碼的問題是<Navbar />
組件將在不關心路由的情況下加載。
您可以簡單地將<Navbar />
組件放入您想要加載的組件中,然后留給其他組件。

TA貢獻1847條經驗 獲得超7個贊
這可能感覺有點作弊,但它確實有效。
從主頁隱藏導航欄(路徑=“/”)非常簡單。我們可以按照書本做,在“Route”中使用渲染。
棘手的部分是如何隱藏 404 錯誤頁面,該頁面與網站中的所有其他路由不匹配。
我使用的技巧是在錯誤頁面掛載時調用 useEffect,將導航欄的樣式更改為顯示:無;
import React from "react";
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";
import "./styles.css";
const NavBar = () => {
return (
<div className="navbar">
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
<Link to="/error">Error</Link>
</div>
);
};
const Home = () => (
<div>
<h1>This is home</h1>
<ul>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</div>
);
const About = () => <div>About</div>;
const Contact = () => <div>Contact</div>;
const Error = () => {
React.useEffect(() => {
document.getElementsByClassName("navbar")[0].style.display = "none";
}, []);
return (
<div>
<h1>Error</h1>
<Link to="/">Back to home</Link>
</div>
);
};
export default function App() {
return (
<Router>
<Route
render={({ location }) => {
if (location.pathname !== "/") return <NavBar />;
}}
/>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={Error} />
</Switch>
</Router>
);
}
body {
margin: 0;
padding: 0;
}
.App {
font-family: sans-serif;
text-align: center;
}
.navbar {
background: black;
color: white;
padding: 10px 20px;
}
.navbar a {
display: inline-block;
padding: 6px 12px;
text-decoration: none;
color: white;
text-transform: uppercase;
}
添加回答
舉報