【问题标题】:Update Navbar css properties when section within viewport视口内的部分时更新导航栏 css 属性
【发布时间】:2022-01-02 09:39:22
【问题描述】:

我正在使用React Intersection Observer 来查看某个部分是否在视口内。

此函数从外部“部分”组件调用。当它被调用时......我希望它改变我的“导航栏”组件中的活动状态,例如,如果我在 AboutSection 视图中滚动,导航栏链接将改变颜色。

// when component within view, do this
export const inView = (section) => {
  console.log(`${section} section is in view`);
};

这是导航栏组件

import Box from "@mui/material/Box";
import Link from "@mui/material/Link";
import "../App.css";

const Navbar = () => {
  return (
    <Box
      component="div"
      id="navbar"
      sx={{
        display: "flex",
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        width: "300px",
        position: "fixed",
        top: "0",
        p: 1,
        boxShadow: 5,
        borderRadius: 2,
        backgroundColor: "primary.main",
        mt: 2,
        animationName: "intro",
        animationDuration: "6s",
        zIndex: "1000",
        "& .nav-link": {
          padding: 1,
          textDecoration: "none",
          color: "primary.light",
        },
        "& .nav-link:hover": {
          color: "secondary.main",
          transform: "scale(1.1)",
          transition: "ease-in 0.2s",
        },
      }}
    >
      <Link href="#home" className="nav-link">
        Home
      </Link>
      <Link href="#about" className="nav-link">
        About
      </Link>
      <Link href="#talents" className="nav-link">
        Talents
      </Link>
      <Link href="#contact" className="nav-link">
        Contact
      </Link>
    </Box>
  );
};
export default Navbar;

这是节组件中的一个 sn-p

const HeroSection = () => {
 // react-intersection-observer functionality
  const elementRef = useRef(null);
  const isOnScreen = useOnScreen(elementRef);
  if (isOnScreen) inView("Hero"); // calls the function described
}

我希望这是有道理的:/

谢谢大家

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    比起更改:active 状态,我认为进行基于类的设置可能更容易(如果CSS 在您的控制范围内)。例如,你可以说如果元素有.active(而不是:active)然后应用一些样式。向元素添加类会更容易 imo。

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      相关资源
      最近更新 更多