当前位置: 首页 > news >正文

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

在这里插入图片描述

在这里插入图片描述

http://www.lryc.cn/news/401641.html

相关文章:

  • 如何在SpringCloud中使用Kafka Streams实现实时数据处理
  • InterSystems IRIS使用python pyodbc连接 windows环境,odbc驱动安装,DSN配置,数据源配置
  • JVM:运行时数据区
  • spring-boot2.x整合Kafka步骤
  • 信创学习笔记(四),信创之数据库DB思维导图
  • SCP 使用教程
  • python自动化之用flask校验接口token(把token作为参数)
  • 旗晟巡检机器人的应用场景有哪些?
  • vue2迁移到vue3注意点
  • 使用windows批量解压和布局ImageNet ISLVRC2012数据集
  • css实现每个小盒子占32%,超出就换行
  • C++的链接指示extern “C“
  • 私域运营 组织架构
  • Netty HTTP
  • 什么是边缘计算技术和边缘计算平台?
  • 自然语言处理(NLP)——法国工程师IMT联盟 期末考试题
  • Linux内核编译安装 - Deepin,Debian系
  • 安全防御,防火墙配置NAT转换智能选举综合实验
  • 追溯源码观察HashMap底层原理
  • 为什么渲染农场渲染的是帧,而不是视频?
  • windows镜像下载网站
  • ollama + fastgpt 搭建免费本地知识库
  • pytorch中一些最基本函数和类
  • 排序——归并排序及排序章节总结
  • python的readline()和readlines()
  • 【ARM】使用JasperGold和Cadence IFV科普
  • 深入探讨极限编程(XP):技术实践与频繁发布的艺术
  • 【代码随想录_Day30】1049. 最后一块石头的重量 II 494. 目标和 474.一和零
  • 【时时三省】tessy 集成测试:小白入门指导手册
  • 通过vagrant与VirtualBox 创建虚拟机