100% width in React Native Flexbox

后端 未结 10 890
日久生厌
日久生厌 2020-12-12 11:51

I have already read several flexbox tutorial, but I still cannot make this simple task to work.

How can I make the red box to 100% width?

Code:

相关标签:
10条回答
  • 2020-12-12 12:48

    just remove the alignItems: 'center' in the container styles and add textAlign: "center" to the line1 style like given below.

    It will work well

    container: {
      flex: 1,
      justifyContent: 'center',
      backgroundColor: '#F5FCFF',
      borderWidth: 1,
    }
    
    line1: {
        backgroundColor: '#FDD7E4',
        textAlign:'center'
    },
    
    0 讨论(0)
  • 2020-12-12 12:52

    Here you go:

    Just change the line1 style as per below:

    line1: {
        backgroundColor: '#FDD7E4',
        width:'100%',
        alignSelf:'center'
    }
    
    0 讨论(0)
  • 2020-12-12 12:52

    Use javascript to get the width and height and add them in View's style. To get full width and height, use Dimensions.get('window').width https://facebook.github.io/react-native/docs/dimensions.html

    getSize() {
        return {
            width: Dimensions.get('window').width, 
            height: Dimensions.get('window').height
        }
    }
    

    and then,

    <View style={[styles.overlay, this.getSize()]}>
    
    0 讨论(0)
  • 2020-12-12 12:52

    width: '100%' and alignSelf: 'stretch' didn't work for me. Dimensions didn't suite my task cause I needed to operate on a deeply nested view. Here's what worked for me, if I rewrite your code. I just added some more Views and used flex properties to achieve the needed layout:

      {/* a column */}
      <View style={styles.container}>
        {/* some rows here */}
        <Text style={styles.welcome}>
          Welcome to React Natives
        </Text>
        {/* this row should take all available width */}
        <View style={{ flexDirection: 'row' }}>
          {/* flex 1 makes the view take all available width */}
          <View style={{ flex: 1 }}>
            <Text style={styles.line1}>
              line1
            </Text>
          </View>
          {/* I also had a button here, to the right of the text */}
        </View>
        {/* the rest of the rows */}
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    
    0 讨论(0)
提交回复
热议问题