feat: replace get-shape with shape hooks

This commit is contained in:
unix
2020-04-01 06:40:29 +08:00
parent 5cbb5cc7f7
commit 8064c51c9c
3 changed files with 48 additions and 28 deletions

View File

@@ -101,29 +101,3 @@ export const setChildrenIndex = (
return item
})
}
export type ShapeType = {
width: number
height: number
}
export const getRealShape = (el: HTMLElement | null): ShapeType => {
const defaultShape: ShapeType = { width: 0, height: 0 }
if (!el || typeof window === 'undefined') return defaultShape
const rect = el.getBoundingClientRect()
const { width, height } = window.getComputedStyle(el)
const getCSSStyleVal = (str: string, parentNum: number) => {
if (!str) return 0
const strVal = str.includes('px') ? +str.split('px')[0]
: str.includes('%') ? +str.split('%')[0] * parentNum * 0.01 : str
return Number.isNaN(+strVal) ? 0 : +strVal
}
return {
width: getCSSStyleVal(`${width}`, rect.width),
height: getCSSStyleVal(`${height}`, rect.height),
}
}

View File

@@ -5,8 +5,8 @@ export type CurrentStateType<S> = [
]
const useCurrentState = <S,>(initialState: S): CurrentStateType<S> => {
const [state, setState] = useState<S>(initialState)
const ref = useRef<S>(initialState)
const [state, setState] = useState<S>(initialState as S)
const ref = useRef<S>(initialState as S)
useEffect(() => {
ref.current = state

View File

@@ -0,0 +1,46 @@
import { MutableRefObject, useEffect, useState } from 'react'
export type ShapeType = {
width: number
height: number
}
export const getRealShape = (el: HTMLElement | null): ShapeType => {
const defaultShape: ShapeType = { width: 0, height: 0 }
if (!el || typeof window === 'undefined') return defaultShape
const rect = el.getBoundingClientRect()
const { width, height } = window.getComputedStyle(el)
const getCSSStyleVal = (str: string, parentNum: number) => {
if (!str) return 0
const strVal = str.includes('px') ? +str.split('px')[0]
: str.includes('%') ? +str.split('%')[0] * parentNum * 0.01 : str
return Number.isNaN(+strVal) ? 0 : +strVal
}
return {
width: getCSSStyleVal(`${width}`, rect.width),
height: getCSSStyleVal(`${height}`, rect.height),
}
}
export type ShapeResult = [ShapeType, () => void]
const useRealShape = <T extends HTMLElement>(ref: MutableRefObject<T | null>): ShapeResult => {
const [state, setState] = useState<ShapeType>({
width: 0,
height: 0,
})
const update = () => {
const { width, height } = getRealShape(ref.current)
console.log(123, 'update')
setState({ width, height })
}
useEffect(() => update(), [ref.current])
return [state, update]
}
export default useRealShape