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>)
}
相关推荐
IT毕设实战小研8 分钟前
基于大数据的DAX40成分股金融新闻情感趋势可视化分析
android·大数据·python·考研·金融·课程设计
Carl_奕然29 分钟前
【智能体】Agent的四种设计模式之:React(2026最新版)
javascript·人工智能·python·react.js·设计模式·语言模型
名为沙丁鱼的猫72931 分钟前
React/JSX 编码规范
前端·javascript·react.js
Android-Flutter1 小时前
flutter async/await 详解
android·flutter
步行cgn1 小时前
Spring Boot 中的 YAML 完全指南
android·spring boot·firefox
事圆则缓2 小时前
Java 常见数据结构与 Android 使用场景
android·java·数据结构
Light Gao2 小时前
企业级移动端 APP 架构设计:从原生双端到 Hybrid、React Native 与 Flutter
flutter·react native·react.js
RisunJan2 小时前
Android 高频面试题与解答
android
MyBili2 小时前
【安卓开发/搞机】快图浏览(QuickPic)技术解析:为何这款3MB应用仍是本地图库的性能天花板?
android·app·安卓·文件管理·相册·看图软件·手机相册
事圆则缓3 小时前
Kotlin 高阶工程化与 Android 深入实践
android·开发语言·kotlin