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>)
}
相关推荐
百锦再4 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
Ashley的成长之路4 小时前
2025 年最新:VSCode 中提升 React 开发效率的必备插件大全
ide·vscode·react.js·工作提效·react扩展
百锦再4 小时前
React编程高级主题:测试代码
android·前端·javascript·react.js·前端框架·reactjs
2501_916008895 小时前
全面介绍Fiddler、Wireshark、HttpWatch、SmartSniff和firebug抓包工具功能与使用
android·ios·小程序·https·uni-app·iphone·webview
玉梅小洋6 小时前
Windows 10 Android 构建配置指南
android·windows
光影少年8 小时前
react的hooks防抖和节流是怎样做的
前端·javascript·react.js
Libraeking8 小时前
视觉篇:Canvas 自定义绘图与高级动画的华丽圆舞曲
android·经验分享·android jetpack
Fushize8 小时前
多模块架构下的依赖治理:如何避免 Gradle 依赖地狱
android·架构·kotlin
Jomurphys9 小时前
Kotlin - 类型别名 typealias
android·kotlin
Haha_bj9 小时前
Flutter ——flutter_screenutil 屏幕适配
android·ios