如何使用useRef钩子去除useEffect的效果?

时间:2021-02-06 20:24:04

标签: javascript reactjs react-hooks use-effect use-ref

我将 useRef 和 useEffect 用于学习目的。在 AppBar 中,我想在单击时使用 useRef 为 Navlink 着色(黄色)。但问题是,当我选择另一个 Navlink 时,如何从第一个 Navlink 移除效果(移除颜色)。 enter image description here

const history = useHistory();

const focusHomeRef = useRef(null);
const focusAdmissionRef = useRef(null);
const focusResultRef = useRef(null);
const focusAboutRef = useRef(null);
const isInitialHome = useRef(true); 

useEffect(() => {
 focusHomeRef.current.style.backgroundColor = "yellow";
},[]);

function focusHome() {
 history.push("/");
 focusHomeRef.current.style.backgroundColor = "yellow";
}

function focusAdmission() {
 history.push("/Admission");
 focusAdmissionRef.current.style.backgroundColor = "yellow";
}

function focusResult() {
 history.push("/Result");
 focusResultRef.current.style.backgroundColor = "yellow";
}

function focusAbout() {
 history.push("/About");
 focusAboutRef.current.style.backgroundColor = "yellow";


return (
 <div>
   <AppBar position="static" >
     <Toolbar>
       
       <IconButton ref={focusHomeRef} onClick={focusHome}>
         <HomeIcon style={{ color: green[500] }} />
         <Avatar alt="Remy Sharp" src="../../styles/img/faces/avatar.jpg" />
         <Typography className={classes.title} variant="h6" noWrap>
           Home
         </Typography>
       </IconButton>

       <div>
         <Button ref={focusAdmissionRef} onClick={focusAdmission}>
           <Typography>Admission</Typography>
         </Button>

         <Button ref={focusResultRef} onClick={focusResult}>
           <Typography>Results</Typography>
         </Button>

         <Button ref={focusAboutRef} onClick={focusAbout}>
           <Typography>About</Typography>
         </Button>
</div>
     </Toolbar>
   </AppBar>
</div>

目标是通过下面的代码行实现的,但它变得太冗长,似乎不是一个好方法。

  useEffect(() => {
    focusHomeRef.current.style.backgroundColor = "yellow";
  });

  function focusHome() {
    history.push("/");
    //if (isInitialHome.current) {
    focusHomeRef.current.style.backgroundColor = "yellow";
    focusAdmissionRef.current.style.backgroundColor = "inherit";
    focusResultRef.current.style.backgroundColor = "inherit";
    focusAboutRef.current.style.backgroundColor = "inherit";
    isInitialHome.current = false;
    // }
  }

  function focusAdmission() {
    history.push("/Admission");
    focusAdmissionRef.current.style.backgroundColor = "yellow";
    isInitialHome.current = false;
    isInitialResult.current = false;
    isInitialAbout.current = false;
  }

在这种情况下,我如何更好地(有效地)使用 useRef 和 useEffect。

0 个答案:

没有答案