【问题标题】:What's the best way to change a global component based on the current route?根据当前路线更改全局组件的最佳方法是什么?
【发布时间】:2021-02-05 19:58:45
【问题描述】:

我正在使用 React 构建一个网站,我希望我的导航栏根据当前路线具有不同的背景颜色。我的 App.js 看起来像这样:

class App extends React.Component {

  render() {
    return (
      <Router>
        <div className="App">
          <div className="Navbar" >
            <Navbar />
          </div>
          <div className="Content">
            <Route path="/" exact render={() => <LandingPage />} />
            <Route path="/about" exact render={() => <AboutPage />} />
            <Route path="/contact" exact render={() => <ContactPage />} />
          </div>
        </div>
      </Router>
    );
  }
}

假设我想要主页(“/”)页面上的透明背景,但其他地方都是纯色,那么在 &lt;Navbar /&gt; 的 CSS 中更改 background 属性以实现什么的最佳方法是什么我要吗?

假设我将要更改的 CSS 属性存储在 this.state 中,然后在路由更改时调用一个函数来更改这些属性?

【问题讨论】:

    标签: html css reactjs react-router


    【解决方案1】:

    您可以使用 context api 来更改任何组件的背景颜色。所以,你只需要根据不同的 url 定义一个上下文值。

    【讨论】:

      猜你喜欢
      • 2015-04-07
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多