React Native 自定义 Hook 获取组件位置和大小

在 React Native 中自定义 Hook useLayout 获取 View、Pressable 等组件的位置和大小的信息

typescript 复制代码
import {useState, useCallback} from 'react'
import {LayoutChangeEvent, LayoutRectangle} from 'react-native'

export function useLayout() {
  const [layout, setLayout] = useState<LayoutRectangle>({
    x: 0,       // 目标元素相对父元素的X轴距离
    y: 0,       // 目标元素相对父元素的Y轴距离
    width: 0,   // 目标元素的宽度
    height: 0,  // 目标元素的高度
  })

  const onLayout = useCallback(
    (e: LayoutChangeEvent) => setLayout(e.nativeEvent.layout),
    [],
  )

  return {
    onLayout,
    ...layout,
  }
}

onLayout 这个在列表组件中弹窗很有用,可以方便的使用它来获取位置信息。

typescript 复制代码
import { useLayout } from './useLayout'
 
 function MyComponent() {
 
    const { x, y, width, height, onLayout } = useLayout()
    
    return (<View style={{height:800,backgroundColor:'#d9f'}}>
	<Pressable onLayout={onLayout} style={{width:100,height:100,backgroundColor:'red'}} />
	<View style={{
		position:'absolute',
		top:y,
		left:x,
		backgroundColor:'#eea',
		width:100,
		height:100
	}}>
		<Text>{`x:${x}`}</Text>
		<Text>{`y:${y}`}</Text>
	</View>
</View>)
}
相关推荐
砖厂小工1 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心2 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心2 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
青青家的小灰灰3 小时前
React 反模式(Anti-Patterns)排查手册:从性能杀手到逻辑陷阱
前端·javascript·react.js
青青家的小灰灰3 小时前
告别 Prop Drilling:Context API 的陷阱、Reducer 模式与原子化状态库原理
前端·javascript·react.js
Kapaseker4 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴5 小时前
Android17 为什么重写 MessageQueue
android
ssshooter17 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
Live0000019 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
阿巴斯甜1 天前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android