【问题标题】:Change header background color on other pages in ReactJS在 ReactJS 中更改其他页面上的标题背景颜色
【发布时间】:2020-10-19 19:51:33
【问题描述】:

我有以下反应代码。

My code

我想要的是,当我点击“主页”菜单背景时,应该在其他情况下变为蓝色。

我写

    style={{background: window.location.pathname == "/" ? "red" : "blue"}}

但它只有在我刷新浏览器时才有效。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    考虑使用useLocation hookuseLocation 允许您通过以下方式获取当前路径:

    let location = useLocation();
    console.log(location.pathname);
    

    所以你的问题可以通过改变你的 Navigation.js 来解决:

    import React from "react";
    import { NavLink, useLocation } from "react-router-dom";
    
    const Navigation = () => (
      <nav
        style={{
          background: useLocation().pathname !== "/" ? "red" : "blue"
        }}
      >
        <ul>
          <li>
            <NavLink exact activeClassName="active" to="/">
              Home
            </NavLink>
          </li>
          <li>
            <NavLink exact activeClassName="active" to="/about">
              About
            </NavLink>
          </li>
          <li>
            <NavLink exact activeClassName="active" to="/contact">
              Contact
            </NavLink>
          </li>
        </ul>
      </nav>
    );
    
    export default Navigation;
    

    你可以看到here的变化。

    【讨论】:

      【解决方案2】:

      一种选择是声明新样式并使用状态变量分配它们

      在 .css 文件中

      .blue {
        background: blue;
      }
      
      .red {
        background: red;
      }
      

      然后如下使用

      import React, {useState} from "react";
      import { NavLink } from "react-router-dom";
      
      const Navigation = (props) => {
        
        const [sitestyle, setStyle] = useState("blue");
      
        return(
        <nav className={sitestyle}>
          <ul>
            <li>
              <NavLink exact activeClassName="active" to="/">
                Home
              </NavLink>
            </li>
            <li>
              <NavLink exact activeClassName="active" to="/about" onClick={() => {setStyle("red")}}>
                About
              </NavLink>
            </li>
            <li>
              <NavLink exact activeClassName="active" to="/contact">
                Contact
              </NavLink>
            </li>
          </ul>
        </nav>
      )
        };
      
      export default Navigation;
      

      【讨论】:

        猜你喜欢
        • 2021-04-15
        • 2021-09-25
        • 1970-01-01
        • 1970-01-01
        • 2013-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        相关资源
        最近更新 更多