如何在 React Native 中跨设备一致地定位元素?



我正在构建一个应用程序,其中包含类似于Instagram上的图像标记的功能。用户可以点击图像,然后从列表中选择标签。然后,我将代码和位置信息保存到 Firebase。

以下是创建和定位这些标记的主要代码:

// Get the location of a tap
handlePress(evt) {
this.top = (evt.nativeEvent.locationY * 100) / SCREEN_HEIGHT;
this.left = (evt.nativeEvent.locationX * 100) / SCREEN_WIDTH;
}
// Create a new View component using the location
tagItem(item) {
const newView = {
locationX: this.left,
locationY: this.top,
item,
};
// Add the new tag to a list of tags
this.setState({
tagList: this.state.tagList.concat([newView]),
});
};

使用SCREEN_HEIGHTSCREEN_WIDTH- 源自 React Native 中的维度 - 是定位元素的最佳方式吗?

我在模拟器和相同尺寸的真实设备上工作正常。但是,我想确保这适用于多种设备尺寸。

谢谢!

只要图像视图在每个设备上的纵横比相同,这应该是可靠的,因为您实际上是将顶部和左侧值存储为高度/宽度的百分比。

最新更新