我想根據導航欄所在的頁面更改導航欄的按鈕樣式,因此我設定了 onclick 處理程式函式,該函式在單擊時更新 useref,但按鈕未更新。
這是我的代碼:
import { Button, Container, Nav, Navbar as NavbarBs } from "react-bootstrap";
import { NavLink } from "react-router-dom";
import CSS from "csstype";
import { useEffect, useRef } from "react";
export function Navbar() {
const buttonDesign = useRef("");
useEffect(() => {});
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
const text = e.currentTarget.firstChild?.textContent;
if (text === "Home") {
console.log(text);
buttonDesign.current = "outline-danger";
} else if (text === "Store") {
console.log(text);
buttonDesign.current = "outline-dark";
}
// Do something
};
return (
<NavbarBs
fixed="top"
style={{
height: "5vh",
position: "fixed",
width: "100%",
background: "transparent",
}}
>
<Container>
<Nav className="d-flex justify-content-between w-100">
<Nav.Link to={"/"} as={NavLink}>
<Button
variant={buttonDesign.current}
style={{
outline: "none",
padding: "5px 50px 5px 50px",
fontFamily: "Playfair Display, serif",
fontSize: "1rem",
}}
onClick={handleClick}
>
Home
</Button>
</Nav.Link>
<Nav.Link to={"/store"} as={NavLink}>
<Button
variant={buttonDesign.current}
style={{
outline: "none",
padding: "5px 50px 5px 50px",
fontFamily: "Playfair Display, serif",
fontSize: "1rem",
}}
onClick={handleClick}
>
Store
</Button>
</Nav.Link>
<Nav.Link to={"/about"} as={NavLink} style={{ color: "white" }}>
<Button
variant={buttonDesign.current}
style={{
outline: "none",
padding: "5px 50px 5px 50px",
fontFamily: "Playfair Display, serif",
fontSize: "1rem",
}}
>
About
</Button>
</Nav.Link>
</Nav>
</Container>
</NavbarBs>
);
}
我嘗試添加一個處理函式以在每次單擊時更新用戶參考,但每次重新渲染時都不會更新 css。
uj5u.com熱心網友回復:
如果目標是根據用戶所在的頁面設定按鈕變體,只需使用 react-router 提供的位置掛鉤而不是處理點擊。
import { useLocation } from "react-router-dom";
在組件中:
const location = useLocation();
const btnDesign = location.pathname === "/" ? "outline-danger" : "outline-dark";
在按鈕中:
variant={btnDesign}
路徑名將由 react 路由器的位置掛鉤更新以保持更新。如果有超過 2 個變體可供選擇,則可以添加更多邏輯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528984.html
