【问题标题】:Conditionally Render CSS Based On Route (React)基于路由有条件地渲染 CSS (React)
【发布时间】:2020-08-16 17:04:59
【问题描述】:

到目前为止,这是我的 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 类标签的样式?我已经看到使用 的示例,但是有没有办法使用 / 来做到这一点?

【问题讨论】:

    标签: css reactjs react-router


    【解决方案1】:

    这样使用

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

    你也可以使用this

    【讨论】:

    • 谢谢 - ClassNames 帮助了。
    猜你喜欢
    • 2019-11-26
    • 2020-01-12
    • 2019-10-05
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2020-11-06
    相关资源
    最近更新 更多