欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > React Native 自定义 Hook 获取组件位置和大小

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

2024/10/24 11:22:27 来源:https://blog.csdn.net/qq_44721831/article/details/140467106  浏览:    关键词:React Native 自定义 Hook 获取组件位置和大小

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

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 这个在列表组件中弹窗很有用,可以方便的使用它来获取位置信息。

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>)
}

在这里插入图片描述

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com