【问题标题】:React Native: how to make View inside ImageBackground have 100% width but with horizontal padding?React Native:如何使 ImageBackground 中的 View 具有 100% 的宽度但具有水平填充?
【发布时间】:2020-08-07 13:01:30
【问题描述】:

我的 React Native 应用程序中有以下屏幕:

蓝黑白背景是ImageBackground,中间的绿条是View。代码是:

<ImageBackground
  source={require('@images/login-background.jpg')}
  style={{
    flex: 1,
    width: '100%',
    resizeMode: 'cover',
    justifyContent: 'center',
  }}
>
  <View style={{
    width: '100%',
    backgroundColor: 'green',
    borderRadius: 15,
    padding: 15
  }}/>
  </ImageBackground>

我希望在绿色View 的左右边缘有填充15px。如果 ImageBackgroundView 我会添加 15px 填充到它,但是当它是 ImageBackground 时会导致:

相反,如果我将margin: 15px 添加到绿色View,我会得到:

我应该如何处理它,让它看起来像这样?

【问题讨论】:

    标签: css reactjs react-native react-native-image imagebackground


    【解决方案1】:

    您可以在 React-Native 中使用 Dimensions 来实现上述要求

    import React from "react";
    import { ImageBackground, View, Dimensions } from "react-native";
    
    const screenWidth = Dimensions.get('window').width;
    
    export default App = () => (
        <ImageBackground
            source={{ uri: "https://reactjs.org/logo-og.png" }}
            style={{
                flex: 1,
                width: '100%',
                resizeMode: 'cover',
                justifyContent: 'center',
                alignItems: 'center'
            }}>
            <View style={{
                width: screenWidth - 30,
                backgroundColor: 'green',
                borderRadius: 15,
                padding: 15
            }} />
        </ImageBackground>
    );
    

    希望这对您有所帮助。如有疑问,请随意。

    【讨论】:

    • 好的,这行得通,谢谢!你知道是否还有一种方法可以使用填充或边距?
    • @gkeenley 当您分配 width: '100%' 时,它会根据父视图自动分配宽度。您可以尝试添加marginHorizontal: 15, width: '90%',但这可能不是最佳解决方案。
    • 是的,不幸的是,如果手机在纵向和横向之间切换,这将不起作用。我会继续使用维度的东西。谢谢!
    【解决方案2】:

    试试这个:

        <ImageBackground
          source={image}
          style={{
            flex: 1,
            width: '100%',
            resizeMode: 'cover',
            justifyContent: 'center',
          }}
        >
        <View style={{paddingHorizontal: 15}}>
          <View style={{
           width: '100%',
           backgroundColor: 'green',
           borderRadius: 15,
           padding: 15,
          }}/>
        </View>
        </ImageBackground>
    

    【讨论】:

    • 这是我的后备解决方案 :) 我宁愿不添加另一个 View 就这样做,但这确实有效,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2015-03-07
    • 2015-08-29
    • 2014-06-02
    • 1970-01-01
    相关资源
    最近更新 更多