Skip to content

Commit

Permalink
chore: 抽离onLayout钩子
Browse files Browse the repository at this point in the history
  • Loading branch information
lareinayanyu committed Oct 17, 2024
1 parent 8630f66 commit 59450c6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
26 changes: 10 additions & 16 deletions packages/webpack-plugin/lib/runtime/components/react/mpx-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { JSX, useRef, forwardRef, ReactNode } from 'react'
import useNodesRef, { HandlerRef } from './useNodesRef'
import useInnerProps, { getCustomEvent } from './getInnerListeners'
import { FormContext } from './context'
import { useTransformStyle, splitProps, splitStyle } from './utils'
import { useTransformStyle, splitProps, splitStyle, useLayoutHook } from './utils'

import { wrapChildren } from './common'

Expand Down Expand Up @@ -40,30 +40,24 @@ const _Form = forwardRef<HandlerRef<View, FormProps>, FormProps>((fromProps: For
} = props

const {
hasPercent,
hasSelfPercent,
normalStyle,
hasVarDec,
varContextRef,
setContainerWidth,
setContainerHeight
setWidth,
setHeight
} = useTransformStyle(style, { enableVar, externalVarContext })

const { textStyle, innerStyle } = splitStyle(normalStyle)

const { nodeRef: formRef } = useNodesRef(props, ref)

const onLayout = (e: LayoutChangeEvent) => {
if (hasPercent) {
const { width, height } = e?.nativeEvent?.layout || {}
setContainerWidth(width || 0)
setContainerHeight(height || 0)
}
if (enableOffset) {
formRef.current?.measure((x: number, y: number, width: number, height: number, offsetLeft: number, offsetTop: number) => {
layoutRef.current = { x, y, width, height, offsetLeft, offsetTop }
})
}
}
const hasLayout = useRef(false)

const onLayout = useLayoutHook({ hasSelfPercent, enableOffset, setWidth, setHeight, layoutRef, nodeRef: formRef }, () => {
hasLayout.current = true
props.onLayout && props.onLayout()
})

const submit = () => {
const { bindsubmit } = props
Expand Down
16 changes: 16 additions & 0 deletions packages/webpack-plugin/lib/runtime/components/react/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,3 +451,19 @@ export function splitProps<T extends Record<string, any>> (props: T): {
innerProps: Partial<T>;
}
}

export const useLayoutHook = ({ hasSelfPercent, enableOffset, setWidth, setHeight, layoutRef, nodeRef }, callback) => {
return (e: LayoutChangeEvent) => {
if (hasSelfPercent) {
const { width, height } = e?.nativeEvent?.layout || {}
setWidth(width || 0)
setHeight(height || 0)
}
if (enableOffset) {
nodeRef.current?.measure((x: number, y: number, width: number, height: number, offsetLeft: number, offsetTop: number) => {
layoutRef.current = { x, y, width, height, offsetLeft, offsetTop }
})
}
callback && callback(e)
}
}

0 comments on commit 59450c6

Please sign in to comment.