usePrevious
记录之前的值。
import { useEffect, useRef } from "react"
function usePrevious<T>(value: T) {
const ref = useRef<T>()
useEffect(() => {
ref.current = value
}, [value])
return ref.current
}
useOnClickOutside
点击元素外,隐藏元素。
type PossibleEvent = {
[Type in HandledEventsType]: HTMLElementEventMap[Type]
}[HandledEventsType]
type Handler = (event: PossibleEvent) => void
function useOnClickOutside(
ref: React.RefObject<HTMLElement>,
handler: Handler) {
useEffect(
() => {
const listener = (event) => {
if (!ref.current || ref.current.contains(event.target)) {
return
}
handler(event)
}
document.addEventListener("mousedown", listener)
document.addEventListener("touchstart", listener)
return () => {
document.removeEventListener("mousedown", listener)
document.removeEventListener("touchstart", listener)
};
},
[ref, handler]
)
}
完善版: use-onclickoutside。
useWindowSize
import { useState, useEffect } from "react"
interface Size {
width: number | undefined;
height: number | undefined;
}
function useWindowSize(): Size {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize, setWindowSize] = useState<Size>({
width: undefined,
height: undefined,
})
useEffect(() => {
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
})
}
window.addEventListener("resize", handleResize);
handleResize()
return () => window.removeEventListener("resize", handleResize)
}, [])
return windowSize;
}