【发布时间】:2018-07-09 13:22:00
【问题描述】:
如何根据我在 React 项目中的路径/页面更改标题颜色?
我看过withRouter,但我不知道如何使用这个例子。
我只想做一些事情,如果路由不是 Home 组件,然后将标题的背景颜色更改为蓝色。似乎这很简单,但无法弄清楚。
【问题讨论】:
标签: reactjs react-router styled-components
如何根据我在 React 项目中的路径/页面更改标题颜色?
我看过withRouter,但我不知道如何使用这个例子。
我只想做一些事情,如果路由不是 Home 组件,然后将标题的背景颜色更改为蓝色。似乎这很简单,但无法弄清楚。
【问题讨论】:
标签: reactjs react-router styled-components
您可以通过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。
【讨论】:
this.props 读取,因此首先确认您是在正确配置的 React 组件中执行此操作。如果这不是问题,我会检查以确保 withRouter 仍然公开 location 值(并且自我最初的回答以来没有弃用它)。
您可以使用withRouter 中的this.props.location 来获取当前路径名。使用它来检查 /home 或任何您的主页,然后您可以向 Header 添加一个更改颜色的类。
【讨论】: