如何根据位置更改 header 背景颜色

How to change header background color in react based on location

如何根据我在 React 项目中的 route/page 更改 header 的颜色?
我看过 withRouter 但我不确定如何使用该示例。
我只想做一些事情,比如如果路由不是 Home 组件,则将 header 的背景颜色更改为蓝色。看起来很简单,但无法弄清楚。

您可以使用 withRouter 中的 this.props.location 来获取当前路径名。使用它来检查 /home 或任何您的主页,然后您可以将 class 添加到 Header 以更改颜色。

您可以通过 withRouter 将组件连接到路由器来使用添加到组件的 location 属性。从那里你可以根据你所在的路由路径应用条件样式。

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class Header extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    const headerColor = location.pathname === 'home' ? { background: 'white'} : { background: 'blue' }
    return (
  <div style={headerColor}>You are now at {location.pathname}</div>
  )
}
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const AdaptiveHeader = withRouter(Header)

export default AdaptiveHeader

对于上面的示例,我重新调整了找到的代码的用途 here