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>)
}
相关推荐
up·1 小时前
react+html-docx-js将页面导出为docx
react.js
刺客-Andy1 小时前
React 第三十九节 React Router 中的 unstable_usePrompt Hook的详细用法及案例
前端·javascript·react.js
Mckay882 小时前
android studio导入项目
android·ide·android studio
是店小二呀4 小时前
【优选算法 | 字符串】字符串模拟题精选:思维+实现解析
android·c++·算法
LuckyLay4 小时前
React百日学习计划-Grok3
前端·学习·react.js
奔跑吧 android5 小时前
【android bluetooth 协议分析 12】【A2DP详解 1】【车机侧蓝牙音乐免切源介绍】
android·bluetooth·bt·gd·a2dpsink·免切源·aosp14
飞猿_SIR6 小时前
Android Exoplayer多路不同时长音视频混合播放
android·音视频
呵呵哒( ̄▽ ̄)"6 小时前
React - 编写选择礼物组件
前端·javascript·react.js
Coding的叶子6 小时前
React Flow 简介:构建交互式流程图的最佳工具
前端·react.js·流程图·fgai·react agent
前端懒猫6 小时前
android实现USB通讯
android