React Native:如何使ImageBackground内的View有100%的宽度,但有水平的padding?

问题描述 投票:0回答:1

在我的React Native应用中,我有以下屏幕。enter image description here

蓝色的黑白背景是一个 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>

我希望有 15px 左右边缘的填充物。View. 如果 ImageBackground 是一个 View 我本想加上 15px 的填充物,但当它是一个。ImageBackground 导致的结果是这样的。

enter image description here

相反,如果我加上 margin: 15px 向绿色 View,我明白了。

enter image description here

我应该如何处理这个问题, 使它看起来像这样?

enter image description here

css reactjs react-native react-native-image imagebackground
1个回答
2
投票

你可以用以下方法实现上述要求 Dimensions 在React-Native中

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>
);

希望对你有所帮助。有疑惑的地方可以随时咨询。


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>
© www.soinside.com 2019 - 2024. All rights reserved.