首页 文章

呈现特定兄弟组件时,Reactjs样式组件的方式不同

提问于
浏览
0

假设我的App.js渲染由下面定义的路由组成, <TopBar> 是网站的导航,它在页面上呈现,无论在路由上方定义渲染的路径,我想要完成的是设置样式 <TopBar> 组件在呈现 /:username 时与在呈现前4个组件时不同 .

App.js

render() {
    return (
      <Router>
        <div className={classnames('app_warapper', {user_app_wrapper:this.props.isAuthenticated, guest_app_wrapper: !this.props.isAuthenticated})}>
          <div className="App">
            <TopBar />
            <Switch>
              <Route exact path="/" component={HomePage} />
              <Route exact path="/login" component={LoginPage} />
              <Route exact path="/signup" component={SignupPage} />
              <Route exact path="/reset" component={ResetPasswordPage} />
              <Route exact path="/reset/:id" component={ResetPasswordPage} />
              <Route exact path="/create-username" component={isAuthenticated(UsernameCreation)} />
              <Route exact path="/dashboard" component={isAuthenticated(DashboardPage)} />
              <Route exact path="/edit-scope/:id" component={isAuthenticated(EditScope)} />
              <Route exact path="/profile" component={isAuthenticated(ProfilePage)} />
              <Route exact path="/logout" component={isAuthenticated(Logout)} />
              <Route exact path="/:username" component={PublicProfilePage} />
              <Route component={NotFound} />
            </Switch>
          </div>
        </div>
      </Router>
    );
  }

我提出的Hacky解决方案我不想使用:

  • 在每个组件中单独渲染 <TopBar> 并将道具传递给它以在 PublicProfilePage 中渲染时使用不同的classNames

  • 在组件装载商店 <TopBar> classNames内 PublicProfilePage ,在组件的持续时间内更改它们,在卸载的组件上设置classNames

1 回答

  • 1

    还有另一个简单的选择 .

    withRouter高阶组件包装 TopBar 组件 .

    export default withRouter(TopBar);
    

    它会将 matchlocationhistory 作为道具注入到 TopBar 组件中,并在每次路径更改时重新渲染组件 . 因此,您可以根据需要有条件地渲染基于这些道具的组件 .

    render() {
        const { match, location, history } = this.props
    
        return (
          //...your conditional JSX for TopBar
        )
    }
    

相关问题