How to change header background color in react based on location

社会主义新天地 提交于 2021-02-19 15:51:16

问题


How do I change my headers color based on what route/page I am on in my React project?
I have looked at withRouter but I am not sure how to use the example.
I just want to do something like if the route is not the Home component then change the background color of the header to blue. Seems like it would be simple but can't figure it out.


回答1:


You can use the location prop that is added to your component by connecting the component to the router via withRouter. From there you apply a conditional style based on which route path you are in.

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

For the above example I repurposed the code found here.




回答2:


You can use this.props.location from withRouter to get the current pathname. Use that to check against /home or whatever your home page is, and then you can add a class to the Header that changes the color.



来源:https://stackoverflow.com/questions/48525120/how-to-change-header-background-color-in-react-based-on-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!