1、React Native獲取組件的寬高
2、以及React Native屏幕dp與px轉換計算;
3、參考:https://www.jianshu.com/p/1198be7e3344
import React, {Component} from 'react';
import {
Text,
View,
findNodeHandle,
UIManager,
TouchableOpacity,
Dimensions,
PixelRatio,
} from 'react-native';
const {width, height} = Dimensions.get('window');
const screenWidth = width;
const screenHeight = height;
const dpToPx = PixelRatio.get();
export default class App extends Component<Props> {
render() {
return (
<TouchableOpacity ref="view" style={{backgroundColor: 'red', flex: 1}}
onPress={() => {
const handle = findNodeHandle(this.refs.view);
UIManager.measure(handle, (x, y, width, height, pageX, pageY) => {
console.log('相對父視圖位置x:', x);
console.log('相對父視圖位置y:', y);
console.log('組件寬度width:', width);
console.log('組件高度height:', height);
console.log('距離屏幕的絕對位置x:', pageX);
console.log('距離屏幕的絕對位置y:', pageY);
console.log('screenWidth: ', screenWidth);
console.log('screenHeight: ', screenHeight);
console.log('dpToPx: ', dpToPx);
console.log('dpToPx * screenWidth: ', dpToPx * screenWidth);
console.log('dpToPx * screenHeight: ', dpToPx * screenHeight);
});
}}>
<Text
ref='text'
style={{marginTop: 100, backgroundColor: 'cyan'}}
onPress={() => {
const handle = findNodeHandle(this.refs.text);
UIManager.measure(handle, (x, y, width, height, pageX, pageY) => {
console.log('相對父視圖位置x:', x);
console.log('相對父視圖位置y:', y);
console.log('組件寬度width:', width);
console.log('組件高度height:', height);
console.log('距離屏幕的絕對位置x:', pageX);
console.log('距離屏幕的絕對位置y:', pageY);
});
}}
>點擊獲取這幾個字的長度</Text>
</TouchableOpacity>
);
}
}
