【问题标题】:Change navbar background-color depending on the page in React根据 React 中的页面更改导航栏背景颜色
【发布时间】:2018-12-11 12:53:12
【问题描述】:

我的主页上有一个透明的导航栏。我想在所有其他页面上给它一个黑色背景。你会怎么做?

上下文:React,没有 Redux。

【问题讨论】:

  • 你用的是什么路由系统?
  • React-router-dom。 navbar 是一个简单的组件,直接添加到 App.js 的渲染部分。

标签: css reactjs navbar


【解决方案1】:

只要检查路线如下:

  import {withRouter} from 'react-router-dom';
    ...

    const SomeComponent = withRouter(props => <MyComponent {...props}/>);

    class MyComponent extends React.Component {
        ...
        SomeMethod () {
          const {pathname} = this.props.location;
          ...
        }
        ...

    }

【讨论】:

    【解决方案2】:

    假设您正确使用 react-router-dom,您可以使用 withRouter HOC 包装您的 Navbar 组件,然后从 this.props.match.path 检索实际位置。

    然后它取决于您使用的样式方法(CSS-in-JS、Styled-Components、Styled-JSX、CSS 模块等)。

    例如,假设您使用 CSS-in-JS,在您的 render 函数中,您可以这样做:

    render () {
      const { match: { path, isExact } } = this.props
      const backgroundStyle = path === '/' && isExact === true 
        ? { backgroundColor: 'transparent' }
        : { backgroundColor: 'black' }
    
      const navbarStyles = {
        ...styles.navbarWrapper,
        ...backgroundStyle
      }
    
      return (
        <div style={navbarStyles}>
          {/* Actual NavBar content here */}
        </div>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2023-03-05
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 2021-10-17
      相关资源
      最近更新 更多