首页 > 解决方案 > 如何在 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_HEIGHTand SCREEN_WIDTH- 从 React Native 中的Dimensions 派生 - 是定位元素的最佳方式吗?

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

谢谢!

标签: javascriptreactjsreact-nativereact-native-androidreact-native-ios

解决方案


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


推荐阅读