【问题标题】:condition in timeout function not working超时功能中的条件不起作用
【发布时间】:2021-03-27 23:03:18
【问题描述】:

我有以下代码,我试图在用鼠标悬停在 div 上时增加它的高度。我想设置一个超时时间,以便在取消悬停时延迟关闭。为了避免当鼠标回到它上面时 div 关闭,我创建了 mouseon 状态,它正在相应地调整,但由于某种原因,它似乎没有在超时功能中调整。为什么?

function Component (props) {

    const [large, setLarge] = useState(false);
    const [mouseon, setMouseon] = useState()

    const handleMouseEnter = () => {
        document.getElementById(`medium`).style.height = '800px';
        setLarge(true);
        setMouseon(true)
    }

    const handleMouseLeave = () => {
        setMouseon(false);
        setTimeout(()=>{
            if(!mouseon){
                document.getElementById(`medium`).style.height = '0px';
                setLarge(false);
            }
        }, 1000);
    }

return (<>
        
                <div id={`medium`}>
                    Something something text
                    {mouseon ? "mouseon" : 0}
                </div>
        </>
    )
}

【问题讨论】:

  • CSS 悬停样式和过渡不是更适合这个吗?您永远不会清除超时,因此如果用户将鼠标悬停,然后关闭,然后重新打开,超时仍在运行。卸载组件时也不会清除超时,这可能会引发有关设置已卸载组件状态的反应错误/警告。直接 DOM 操作通常也被认为是 react 中的一种反模式。
  • 在 React 中,绝不能通过 DOM API 处理原始 DOM。如果您愿意,请改用 useRef 钩子。

标签: javascript reactjs conditional-statements timeout


【解决方案1】:

这是因为当你调用 setTimeout 时你的鼠标状态没有改变。您可以使用 useEffect 来检查状态 mouseon 是否已更改并调用 setTimeout。

const handleMouseLeave = () => {
  setMouseon(false);
};

useEffect(() => {
  setTimeout(() => {
    if (!mouseon) {
      document.getElementById(`medium`).style.height = "0px";
      setLarge(false);
    }
  }, 1000);
}, [mouseon]);

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 2016-08-09
    • 2023-03-24
    • 1970-01-01
    • 2020-04-05
    • 2012-11-29
    • 2019-04-08
    • 2022-11-17
    相关资源
    最近更新 更多