React Native 自定义 Hook 获取组件位置和大小
warning:
这篇文章距离上次修改已过183天,其中的内容可能已经有所变动。
import React, { useRef, useEffect, useState } from 'react';
import { View, StyleSheet } from 'react-native';
export const useComponentPosition = () => {
const ref = useRef(null);
const [position, setPosition] = useState({ x: 0, y: 0, width: 0, height: 0 });
useEffect(() => {
if (ref.current) {
const handleLayout = (e) => {
const { x, y, width, height } = e.nativeEvent.layout;
setPosition({ x, y, width, height });
};
ref.current.addEventListener('layout', handleLayout);
return () => {
ref.current.removeEventListener('layout', handleLayout);
};
}
}, [ref.current]);
return { ref, position };
};
const MyComponent = () => {
const { ref, position } = useComponentPosition();
return <View ref={ref} style={styles.myComponent} />;
};
const styles = StyleSheet.create({
myComponent: {
width: 100,
height: 100,
backgroundColor: 'blue',
},
});
这段代码定义了一个自定义钩子 useComponentPosition
,用于获取组件的位置和尺寸。它返回一个带有 ref
属性的对象,以及一个包含位置和尺寸信息的 position
状态。在组件 MyComponent
中使用这个钩子时,它会在组件加载时获取布局信息,并在卸载时移除监听器,以防止内存泄漏。
评论已关闭