[英]Reactjs style component differently when specific sibling component is rendered
Say my App.js render consists of the routes defined below, <TopBar>
is the site's navigation and it gets rendered on the page regardless of the route that gets rendered as it is defined above the routes, and what I want to accomplish is to style the <TopBar>
component differently when /:username
is rendered vs when the first 4 components are rendered. 假设我的App.js渲染由下面定义的路线组成, <TopBar>
是网站的导航,并且它会在页面上渲染,而与在路线上方定义的要渲染的路线无关,我要做的是呈现/:username
时与呈现前四个组件时, <TopBar>
组件的样式不同。
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 solutions I came up with that I don't want to use: 我想出了我不想使用的hacky解决方案:
<TopBar>
in every component individually and pass props to it to use different classNames when rendered inside PublicProfilePage
<TopBar>
在每个组件中渲染<TopBar>
,并将其传递给道具,以在PublicProfilePage
渲染时使用不同的className PublicProfilePage
on component mounting store <TopBar>
classNames, change them for duration of the component, on component getting dismounted set the classNames back 内部PublicProfilePage
上部件安装存储<TopBar>
类名,改变它们的组分的持续时间,取决于组分得到拆卸设置的类名背面 There is another simple alternative. 还有另一个简单的选择。
Wrap your TopBar
component with withRouter
higher-order component. 用withRouter
高阶组件包装TopBar
组件。
export default withRouter(TopBar);
It will inject match
, location
, history
as props to your TopBar
component and re-render the component when every time the route changes. 它将match
, location
, history
作为道具注入到TopBar
组件中,并在每次路线更改时重新渲染该组件。 So you can conditionally render the component based on these props as you want. 因此,您可以根据需要根据这些道具有条件地渲染组件。
render() {
const { match, location, history } = this.props
return (
//...your conditional JSX for TopBar
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.