是否有功能可根据网站路径隐藏组件?

时间:2020-10-11 16:09:48

标签: javascript reactjs jsx

在我的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>

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

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

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

4 个答案:

答案 0 :(得分:1)

您可以创建一个高阶组件,以一个页脚呈现一个组件,然后可以在/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>

另一种解决方案是在使用Footer提供的window.locationuseParams()钩子检查URL之后,有条件地呈现react-router-dom组件,但是useParams()仅在以下情况下有效您的组件是使用React Router渲染的。对于您的情况,您将需要window.location

答案 1 :(得分:0)

Footer组件中,您只需检查window.location.pathname是否包含/test并返回null

答案 2 :(得分:0)

如果您不熟悉HOC模式,另一种选择是将<Footer/>组件仅呈现在需要它的组件内部而不是顶层。

答案 3 :(得分:0)

您可以在页脚中检查路线详细信息,并根据情况进行渲染。如果您使用钩子,则React Router> = 5.1随useRouteMatch一起提供。如果您改用类(或较旧的React Router),则需要使用withRouter High-Order Component。您还可以自己检查窗口的位置,但是我建议您使用已经通过React Router提供的工具。

带有钩子的示例

function Footer() {
  const match = useRouteMatch("/test");

  // You can also use match.isExact when it's avaible to narrow
  // the check down to specifically "/test" but still keep urls
  // such as "/test/some/other/path"
  if (match /*&& match.isExact*/) return null;

  return <footer>This is the footer</footer>;
}

具有较高阶分量的示例

class FooterWithRouter extends Component {
  render() {
    if (this.props.location.pathname === "/test") {
      return null;
    }

    return <footer>This is the footer</footer>;
  }
}
const Footer = withRouter(FooterWithRouter);

CodeSandbox用于代码示例 https://codesandbox.io/s/runtime-cdn-v7icj

https://v7icj.csb.app/ https://v7icj.csb.app/test