【问题标题】:React Native ScrollView with absolutely positioned children relative to screen sizeReact Native ScrollView 与相对于屏幕大小的绝对定位的子项
【发布时间】:2021-07-23 03:10:00
【问题描述】:

我有一个水平的 ScrollView 组件,它在 React Native 中包裹了整个屏幕,它的第一个子组件是一个占据整个设备高度的图像,并延伸到设备宽度之外。我试图在背景图像中绝对定位元素,以便它们在不同设备上始终处于与背景相同的相对位置,但我不知道如何。任何帮助将不胜感激。

当前代码示例:

<View style={styles.container}>
  <ScrollView horizontal={true} bounces={false}>
    <ImageBackground style={styles.backgroundImage}>
      <Element style={{position: "absolute", top: "30%", left: "50%"}}>
    </ImageBackground>
  </ScrollView>
</View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    height: SCREEN.height,
  },
  backgroundImage: {
    height: SCREEN.height,
    width: SCREEN.height * 1.125,
  },
})

问题是具有绝对定位的元素最终会在不同设备上的背景图像的不同位置。有可能解决这个问题吗?

【问题讨论】:

    标签: css react-native scrollview horizontalscrollview


    【解决方案1】:

    问题在于&lt;ImageBackground /&gt; 类。根据 React-Native 文档,图像适合整个可用空间,而不会丢失原始图像的宽高比,这会导致图像缩放,在这种情况下,开发人员可以控制缩放因子。

    <Element style={{position: "absolute", top: "30%", left: "50%"}}>
    

    对于上面的Element类,你只能在使用%position: absolute时将其定位在屏幕的宽度和高度上。

    总而言之,您的 Elements 类样式代码是完美的,问题在于 &lt;ImageBackground /&gt; 类。

    而且所有设备都有不同的纵横比,因此使用这个:

        width: SCREEN.height * 1.125,
    

    可能不是最好的选择。

    你可以这样做:

    import {View, ScrollView, Dimension} from react-native;
    const {width: viewportWidth, height: viewportHeight} = Dimensions.get('window');
    
    <View style={styles.container}>
       <ScrollView horizontal={true} bounces={false}>
          <ImageBackground style={styles.backgroundImage}>
             <Element style={{position: "absolute", top: "30%", left: "50%"}}>
          </ImageBackground>
       </ScrollView>
    </View>
    
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      backgroundImage: {
        height: viewportHeight,
        width: viewportWidth,
      },
    })
    

    我希望这是您正在寻找的。干杯伙伴!

    【讨论】:

    • 感谢 Gavin 的深入回复。问题是背景图像需要比屏幕宽度长很多,因此需要水平滚动视图。添加到图像中的 1.125 占其自身的比例,而不是屏幕的比例。
    • @ahrampy 我想我理解这个问题并且也有解决方案,但只需要确认我们是否在同一页面上。您能否分享例外 ui 和您在设备上获得的实际 ui 的屏幕截图?
    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2018-04-01
    • 2021-01-20
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多