useHover 也就是滑鼠移入移出事件
直接寫範例
import React, { useRef, useState, useEffect } from 'react';
export default function App() {
const [hover, isHover] = useHover();
return (
<div ref={hover}>
{isHover ? 'yes' : 'NO'}
</div>
)
}
// Hook
const useHover = () => {
const [value, setValue] = useState(false);
const ref = useRef(null);
const handleMouseOver = () => setValue(true);
const handleMouseOut = () => setValue(false);
useEffect(() => {
const node = ref.current;
if (node) {
node.addEventListener('mouseover', handleMouseOver);
node.addEventListener('mouseout', handleMouseOut);
}
});
return [ref, value];
}
輸出畫面
useRef 在hook裡面會很常出現,因為hook寫出來就像是套件工具一樣,一個hook多個組件一起用,這也是hook最方便的地方,而且hook其實也不用自己寫,很多套件可以使用,等真的摸透了再來開發hook才是真正學會React