是否有功能可以根据网站路径隐藏组件? [英] Is there a function in react to hide a component based on the website path?

查看:67
本文介绍了是否有功能可以根据网站路径隐藏组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的React应用中,我目前有这个:

In my react app I currently have this:

<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>

但是,如果路由路径为"/test",则我希望隐藏页脚元素. 这比编写要干净得多:

However I want the footer element to be hidden if the route path is "/test" It would be a lot cleaner than writing:

<Route path="/roles" exact component={Footer} />
<Route path="/rules" exact component={Footer} />
<Route path="/" exact component={Footer} />

如果有人知道执行此操作的功能,将不胜感激.

If anyone knows the function to do this it would be greatly appreciated.

推荐答案

您可以创建一个高阶组件,该组件用页脚呈现一个组件,然后可以在除.

You could create a higher-order component that renders a component with a footer and then you could render that higher-order component at all the paths other than /test.

高阶组件仅使用应与Footer组件一起显示的组件,并返回另一个仅将包装后的组件与Footer组件一起呈现的组件.

Higher-order component just takes a component that should be displayed with a Footer component and returns another component that just renders the wrapped component along with the Footer component.

function WithFooter(WrappedComponent) {
  const EnhancedComponent = (props) => {
    return (
      <>
        <WrappedComponent {...props} />
        <Footer />
      </>
    );
  };

  return EnhancedComponent;
}

此后,无需导出PersonList组件,而是需要导出通过调用WithFooter高阶组件返回的组件,如下所示:

After this, instead of exporting PersonList component, you need to export the component returned by calling WithFooter higher-order component as shown below:

function PersonList() {
  ...
}

export default WithFooter(PersonList);

您还需要对其他使用Footer呈现的组件执行相同的操作.

You need to do the same for other components as well that should be rendered with a Footer.

通过设置所有高阶组件,您的路线定义无需更改:

With higher-order component all set-up, your routes definition don't need to change:

<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.locationuseParams()钩子检查URL之后,有条件地呈现Footer组件,但是useParams()仅在使用react router呈现组件时才起作用.就您而言,您将需要window.location.

Alternative solution is to conditionally render the Footer component after checking the URL using window.location or useParams() hook provided by react-router-dom but useParams() will only work if your component is rendered using react router. In your case, you will need window.location.

这篇关于是否有功能可以根据网站路径隐藏组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆