[英]React with FlowRouter: How to show/hide component based on route
我有一個Meteor
應用程序,我正在使用React
開發,我使用FlowRouter
進行路由。 我項目的主要AppContainer
有很多組件,其中一個是頁腳。
class AppContainer extends Component {
render() {
return(
<div className="hold-transition skin-green sidebar-mini">
<div className="wrapper">
<Header user={this.props.user} />
<MainSideBar />
{this.props.content}
<Footer />
<ControlSideBar />
<div className="control-sidebar-bg"></div>
</div>
</div>
)
}
}
我有幾條路線可以進入各種聊天室:
例如。
/chatroom/1
/chatroom/2
/chatroom/3
如果路線是/chatroom/<anything>
有沒有辦法隱藏<Footer />
組件?
您可以通過檢查當前路徑來執行條件渲染。
如果/chatroom/
之后的<anything>
部分(我假設它是一個參數)並不重要,如果你沒有任何其他以chatroom開頭的路由,你可以試試這個:
const currentPath = window.location.pathname
{!currentPath.includes('chatroom') ? <Footer /> : null }
所以你的代碼看起來像這樣:
class AppContainer extends Component {
render() {
currentPath = window.location.pathname
return(
<div className="hold-transition skin-green sidebar-mini">
<div className="wrapper">
<Header user={this.props.user} />
<MainSideBar />
{this.props.content}
{!currentPath.includes('chatroom')
? <Footer />
: null }
<ControlSideBar />
<div className="control-sidebar-bg"></div>
</div>
</div>
)
}
}
如果<anything>
部分很重要和/或您有其他以聊天室開頭的路由,您可以先獲取路徑的參數
const param = FlowRouter.getParam('someParam');
然后通過檢查當前路徑是否包含聊天室/:param來執行條件渲染:
const currentPath = window.location.pathname
{!currentPath.includes(`chatroom/${param}`) ? <Footer /> : null }
所以你的代碼看起來像這樣
class AppContainer extends Component {
render() {
const currentPath = window.location.pathname
const param = FlowRouter.getParam('someParam');
return(
<div className="hold-transition skin-green sidebar-mini">
<div className="wrapper">
<Header user={this.props.user} />
<MainSideBar />
{this.props.content}
{!currenPath.includes(`chatroom/${param}`)
? <Footer />
: null }
<ControlSideBar />
<div className="control-sidebar-bg"></div>
</div>
</div>
)
}
}
您還可以使用以下語法。 它完成了與Cagri Yardimci提供的第一個例子相同的事情。
{ !currentPath.includes('chatroom') && <Footer /> }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.