问题描述
如何根据我在 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.
这篇关于如何根据位置在反应中更改标题背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!