【问题标题】:How to change header background color in react based on location如何根据位置更改标题背景颜色
【发布时间】:2018-07-09 13:22:00
【问题描述】:

如何根据我在 React 项目中的路径/页面更改标题颜色?
我看过withRouter,但我不知道如何使用这个例子。
我只想做一些事情,如果路由不是 Home 组件,然后将标题的背景颜色更改为蓝色。似乎这很简单,但无法弄清楚。

【问题讨论】:

    标签: reactjs react-router styled-components


    【解决方案1】:

    您可以通过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

    【讨论】:

    • 这个答案是有道理的,但是,当我自己尝试时,我收到 typeError: cannot read property 'location' of undefined。有什么建议吗?
    • @Jschriemer 位置应从this.props 读取,因此首先确认您是在正确配置的 React 组件中执行此操作。如果这不是问题,我会检查以确保 withRouter 仍然公开 location 值(并且自我最初的回答以来没有弃用它)。
    【解决方案2】:

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

    【讨论】:

    • 感谢您的帮助。 Alexei Darmin 刚刚让我点击了它。
    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    相关资源
    最近更新 更多