在我的react应用程序中,我目前有这个:
<Router>
<div class Name="App">
<Route path="/" exact component={PersonList} />
<Route path="/rules" exact component={RulesPage} />
<Route path="/roles" exact component={RolesPage} />
<Route path="/test" exact component={Test} />
<Footer />
</div>
</Router>
然而,如果路由路径是"0",我希望页脚元素被隐藏/测试";这将比写干净得多
<Route path="/roles" exact component={Footer} />
<Route path="/rules" exact component={Footer} />
<Route path="/" exact component={Footer} />
如果有人知道这样做的功能,我们将不胜感激。
您可以创建一个高阶组件来渲染带有页脚的组件,然后您可以在除/test
之外的所有路径上渲染该高阶组件。
高阶组件只获取一个应该与Footer
组件一起显示的组件,并返回另一个仅与Footer
组件一起渲染封装组件的组件。
function WithFooter(WrappedComponent) {
const EnhancedComponent = (props) => {
return (
<>
<WrappedComponent {...props} />
<Footer />
</>
);
};
return EnhancedComponent;
}
之后,您不需要导出PersonList
组件,而是需要导出调用WithFooter
高阶组件返回的组件,如下所示:
function PersonList() {
...
}
export default WithFooter(PersonList);
对于应该使用Footer
渲染的其他组件,也需要执行同样的操作。
有了更高阶的组件设置,您的路线定义无需更改:
<Router>
<Route path="/" exact component={PersonList)} />
<Route path="/rules" exact component={RulesPage} />
<Route path="/roles" exact component={RolesPage} />
<Route path="/test" exact component={Test} />
</Router>
另一种解决方案是,在使用react-router-dom
提供的window.location
或useParams()
挂钩检查URL后,有条件地渲染Footer
组件,但useParams()
只有在使用react router渲染组件时才起作用。在您的情况下,您将需要window.location
。
在Footer
组件中,您只需检查window.location.pathname
是否包括/test
,然后返回null
如果您不熟悉HOC模式,另一个选项是只在需要<Footer/>
组件的组件内部渲染,而不是在顶级渲染。