如何在 React 路由器上更改 header 背景?

How to Change header background on react router?

我是新手,尝试根据我所在的路由器路径动态更改 header 的背景。我不想用 redux.

我尝试实施 withrouter,但没有成功。我最难理解的部分是如何在路由之外更改组件的 class 。就我而言,我必须更改为特定的 class.

<Menu className="White"/> // <- wanna change this className="" based on the route
<Switch>
<Route exact path="/" component={Home} /> // <- this should have White className menu  <Menu className="white" />
<Route exact path="/lala" component={lala} /> // <- this should have Black className menu <Menu className="black" />
</Switch>

我希望当我改变路线时,我的菜单 (Header) 颜色会改变。

您可以将 props 从路由传递到组件,

<Switch>
<Route exact path="/" render={() => {
<Home cls="white">}} />
<Route exact path="/lala" render={() => {
<lala cls="black">}} />
</Switch>

然后在你的组件中你可以使用这个,

<Menu className={this.props.cls}/>

您可以使用

呈现菜单
<Route component={Menu} />

但是您需要将样式移动到菜单组件内部。

这将为菜单组件提供路由器道具,因此您可以检查 location 并根据需要设置样式。

所以如果你尝试这样的事情:

function MenuComponent(props) {
  const [className, setClassName] = useState("white")

  useEffect(function() {
    setClassName(props.match.path === "/lala" ? "yellow" : "white")
  }, [props.match.path])

  return (
    <div className={className}>
      ...etc
    </div>
  )
}

export const Menu = withRouter(MenuComponent)

withRouter 是你可以包装组件的东西,包装的组件将接收所有路由器道具,如匹配和历史记录。然后,您可以检查路径是否在效果或 componentDidUpdate 之类的过程中发生变化,然后相应地更新组件的 class。

您还可以创建一个类似这样的检查器:


const currentUrl= window.location.href

const clsColor=
 if(currentUrl.contains('/url-1'){ //or .includes()
    return: 'red'
  }else if(currentUrl.contains('/url-2')
    return: 'white'
  }else{
    return: 'default-color'
  }
// you can also use a cslColor = currentUrl.includes('/url-3') ? 'red' : 'white'

我的长官给我这个简单的解决方案:

import * as cn from 'classnames' 

    const Menu: React.FC<Props> = ({className, children, authenticated, handleAuthentication, location}) => {
        function isHome() {
            return location.pathname === '/' ? true : false;
        }

        return(
                <div className={cn('mydefaultclass', {'bgwhite': !isHome()}, className)}>
//etc
)}

而在我的 App.tsx 中,我只是保持我的路线不变。所以在这种情况下,我的家应该有透明背景,所以采用默认值 class,当我走其他路径时,我的背景变成白色。

所以我只添加了这个逻辑

 function isHome() {
                return location.pathname === '/' ? true : false;
            }

还有这个

{'bgwhite': !isHome()}