根据路线有条件地渲染CSS(反应)

时间:2020-08-16 17:04:59

标签: css reactjs react-router

到目前为止,这是我的App.js组件:

function App() {
  return (
    <div className="App">
      <Router>
        <NavBar />
        <Switch>
         <Route exact path='/' component={HomepageLayout} />
         <Route exact path='/post/:id' component={Post}/>

        </Switch>
      </Router>
    </div>
  );
}

我需要根据要渲染的路由来渲染类的CSS值。呈现HomepageLayout组件时,我需要以下内容:

styles.css

 .ui.inverted.vertical.center.aligned.segment{
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    z-index: 2;  
 }

然后,我需要在渲染Post组件时更改此目标的值,以便基本上删除样式:

styles.css

 .ui.inverted.vertical.center.aligned.segment{
    position: none;
    left: none;
    top: none;
    width: none;
    z-index: none;  
 }

有没有一种方法可以根据路由来更改特定CSS类标签的样式?我已经看到了使用的示例,但是有一种方法可以使用/吗?

1 个答案:

答案 0 :(得分:1)

像这样使用它

<Component header />

// component

const Component = ({header}) => {

  const conditionalClass = header ? 'yesHeader' : 'noHeader';
  return (
   <p className={conditionalClass}>this is </p>
  )

}

您也可以使用this