是ReactJS的新手。我想在登录页面中隐藏标题组件并在内页中显示。我有一个App.js我使用了三元运算符但没有工作。
class App extends Component {
render(){
let HideHeader = EmployeeLogin ? null : <HeaderNavContainer />
return (
<div>
<Router history={history}>
<div>
{HideHeader}
<Switch>
<Route path="/about" component={About} />
<Route path="/EmployeeLogin" component={EmployeeLogin} />
<Route path="/MyPreferences" component={MyPreferences} />
<Route component={PageNotFound} />
</Switch>
</div>
</Router>
</div>
);
}
}
如果渲染了EmployeeLogin组件,我想隐藏标题导航
<HeaderNavContainer />
如果不是,我想展示<HeaderNavContainer />
答案 0 :(得分:5)
在render
的{{1}}方法中,您可以执行此操作:
HeaderNavContainer
由于render() {
if (window.location.pathname === '/EmployeeLogin') return null;
return <insert your header nav code>;
}
已包含在HeaderNavContainer
中,因此<Router>
更改后会重新呈现。
或者,将window.location.pathname
添加到HeaderNavContainer
,About
等,而不是加入MyPreferences
。
答案 1 :(得分:3)
在组件中,您可以检查history.location.pathname
是否等于/EmployeeLogin
,然后返回null。您可以使用withReducer
将历史对象作为道具。
render(){
if(this.props.history.location.pathname==='/EmployeeLogin'){
return null;
}
return (//your navigation component code.)
}
答案 2 :(得分:1)
而不是检查组件是否存在尝试检查URL是否被命中
在window.location.pathname中,您将获得当前网址。
让HideHeader = window.location.pathname ==='你的需要字符串'? null: