React Router 4 - 打开“/"时隐藏导航;路线 [英] React Router 4 - Hide Navigation when on "/" route
本文介绍了React Router 4 - 打开“/"时隐藏导航;路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,带有这样的导入:
import {BrowserRouter 作为路由器,转变,路线,关联来自'反应路由器-dom'从'./Comics'导入{漫画};从'./Books'导入{书籍};从'./Projects'导入{项目};从'./Navigation'导入{导航};功能应用(){返回 (<路由器><div className="应用程序"><导航loggedInUser={loggedInUser}/><Route path="/" 精确组件={Home}/><开关><Route path="/comics" component={Comics}/><Route path="/books" component={Books}/><Route path="/projects" component={Projects}/></开关>
</路由器>)}
如何在/"路线上隐藏导航?我可以在每条路线上渲染导航,但我认为这在性能方面不是一个好主意?
解决方案
Route 的 path 参数可以理解任何与 path-to-regexp 这样您就可以选择仅在路径中像这样的斜杠后至少有一个字符时才呈现导航组件
<导航loggedInUser={loggedInUser}/>)}/>
I have a following code, with such imports:
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom'
import { Comics } from './Comics';
import { Books } from './Books';
import { Projects } from './Projects';
import { Navigation } from './Navigation';
function App() {
return (
<Router>
<div className="App">
<Navigation loggedInUser={loggedInUser} />
<Route path="/" exact component={Home} />
<Switch>
<Route path= "/comics" component={Comics} />
<Route path="/books" component={Books}/>
<Route path="/projects" component={Projects} />
</Switch>
</div>
</Router>
)
}
How to hide navigation when I am on "/" route? I could render Navigation on each route but I don't think this is a good idea performance wise?
解决方案
The path parameter to Route understands any regex compatible with path-to-regexp so you could choose to render the Navigation component only when there is at least one character in the path after the slash like this
<Route path="/(.+)" render={(() =>
<Navigation loggedInUser={loggedInUser} />
)}/>
这篇关于React Router 4 - 打开“/"时隐藏导航;路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文