【问题标题】:Condition rendering of components on BrowserRouterBrowserRouter上组件的条件渲染
【发布时间】:2018-06-06 14:50:40
【问题描述】:

在我的 App.js 中,我有以下功能:

render() {
  return (
    <div>
      <BrowserRouter>
        <div>
          <Header />
          <Alerts />
          <Switch>
            <Route exact path="/" component={Landing} />
            <Route exact path="/signup" component={Signup} />
            <Route exact path="/login" component={Login} />
            <Route exact path="/profile" component={Profile} />
            <Route path="/:folderName" component={Business} />
          </Switch>
        </div>
      </BrowserRouter>
    </div>
  );
}

我想要做的是渲染组件,只在前 4 个路由上,而不是在 /:folderName 路由中。 我可以将 Header 放在每个 Landing、Signup、Login 和 Profile 路由中,但我觉得必须有更好的方法。我也可以像这样使用 render= 而不是 component=:

<Route exact path="/" render={() => (
                  <Fragment>
                    <Header />
                    <Landing />
                  </Fragment>
                )}
/>

但是有更好的方法吗?可以有条件渲染 Header 吗?

谢谢

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

Antonio Pangallo 建议使用 HOC 的评论确实效果最好。这是我的 Switch 现在的样子:

render() {
  return (
    <div>
      <BrowserRouter>
        <div>
          <Switch>
            <Route exact path="/" component={withHeaderAndAlerts(Landing)} />
            <Route exact path="/signup" component={withHeaderAndAlerts(Signup)} />
            <Route exact path="/login" component={withHeaderAndAlerts(Login)} />
            <Route exact path="/profile" component={withHeaderAndAlerts(Profile)} />
            <Route path="/:folderName" component={Business} />
          </Switch>
        </div>
      </BrowserRouter>
    </div>
  );
}

以及用 Header 和 Alerts 包装组件的功能:

//HOC to wrap component in the Header and Alerts components
function withHeaderAndAlerts(WrappedComponent) {
  class withHeaderAndAlerts extends React.Component {
    render() {
      return (
        <Fragment>
          <Header />
          <Alerts />
          <WrappedComponent />
        </Fragment>
      );
    }
  }

  withHeaderAndAlerts.displayName = `withHeaderAndAlerts(${getDisplayName(WrappedComponent)})`;
  return withHeaderAndAlerts;
}

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || "Component";
}

谢谢安东尼奥!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2019-08-07
    • 1970-01-01
    • 2018-04-21
    • 2022-09-24
    • 2021-06-07
    • 2018-09-10
    • 1970-01-01
    相关资源
    最近更新 更多