如何根据位置在反应中更改标题背景颜色 [英] How to change header background color in react based on location

查看:75
本文介绍了如何根据位置在反应中更改标题背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据我在 React 项目中所在的路由/页面更改标题颜色?
我查看了 withRouter,但不确定如何使用该示例.
我只想做一些事情,如果路由不是 Home 组件,然后将标题的背景颜色更改为蓝色.看起来很简单,但无法弄清楚.

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.

推荐答案

您可以使用添加到您的组件中的 location 属性,方法是通过 withRouter.从那里您根据您所在的路线路径应用条件样式.

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.

这篇关于如何根据位置在反应中更改标题背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆