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 小时前
【android 驱动开发九】生产者-消费者模型
android·驱动开发
知识分享小能手2 小时前
React学习教程,从入门到精通, React 新创建组件语法知识点及案例代码(11)
前端·javascript·学习·react.js·架构·前端框架·react
android_xc3 小时前
Android Studio适配butterknife遇到的坑
android·ide·android studio·butterknife
2501_915918413 小时前
uni-app 项目 iOS 上架效率优化 从工具选择到流程改进的实战经验
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张3 小时前
如何在不同 iOS 设备上测试和上架 uni-app 应用 实战全流程解析
android·ios·小程序·https·uni-app·iphone·webview
举个栗子dhy5 小时前
解决在父元素上同时使用 onMouseEnter和 onMouseLeave时导致下拉菜单无法正常展开或者提前收起问题
前端·javascript·react.js
米豆同学5 小时前
SufraceFlinger图像合成原理(3)-SurfaceFlinger中Layer的创建和销毁
android
米豆同学5 小时前
SufraceFlinger图像合成原理(2)-SurfaceFlinger与应用进程间的通信
android
用户2018792831675 小时前
uses-library:系统应用报NoClassDefFoundError问题
android