【问题标题】:How to set the style attribution to fill the rest space?如何设置样式属性以填充剩余空间?
【发布时间】:2017-03-16 14:11:37
【问题描述】:

如您所见,如果三个红色视图已添加到父视图上。现在我想添加另一个可以填充剩余空间的蓝色视图。如何设置样式?

【问题讨论】:

    标签: react-native flexbox


    【解决方案1】:

    你可以试试这个;

    <View style={{flex:1,backgroundColor:'white'}}>
      <View style={{justifyContent:'space-around'}}>
        <View style={{height:50,alignSelf:'stretch',backgroundColor:'pink',margin:5}}/>  
        <View style={{height:50,alignSelf:'stretch',backgroundColor:'pink',marginHorizontal:5}}/>  
        <View style={{height:50,alignSelf:'stretch',backgroundColor:'pink',margin:5}}/>  
      </View>
      <View style={{flex:1,alignItems:'center',justifyContent:'center',alignSelf:'stretch',backgroundColor:'blue',margin:5}}>
        <Text style={{color:'white',fontWeight:'bold'}}>
          View
        </Text>
      </View>
    </View>
    

    【讨论】:

    • 我试了一下,还是不行。我想''flex''在其他孩子也有这个属性时很有用,并且也通过数字分配这些孩子的空间。
    • 它对我不起作用,但我放置了所有样式 StyleSheet.create 并且它起作用了。显然,在内联样式中使用flex: 1 时可能会出现错误
    • flex: 1 和 alignSelf: 'stretch' 为我工作。
    【解决方案2】:

    更简单的解决方案是在要填充剩余空间的视图上使用属性flexGrow: 1

    flexGrow 描述了容器内的任何空间应如何沿主轴分布在其子级之间。在布置完其子级后,容器将根据其子级指定的弹性增长值分配任何剩余空间。

    flexGrow 接受任何 >= 0 的浮点值,其中 0 是默认值。容器将根据孩子的弹性增长值在其孩子之间分配任何剩余空间。

    https://facebook.github.io/react-native/docs/flexbox

    DEMO

    代码

    import * as React from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    
    export default class App extends React.Component {
      render() {
        return (
          <View style={styles.container}>
            <View style={styles.flexContainer}>
              <View style={styles.box1}></View>
              <View style={styles.box2}></View>
            </View>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        padding: 8,
      },
      flexContainer: {
        backgroundColor: 'black',
        height: 100,
        flexDirection: 'row'
      },
      box1: {
        backgroundColor: 'blue',
        width: 100,
        height: '100%'
      },
      box2: {
        backgroundColor: 'red',
        height: '100%',
        flexGrow: 1
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-06-12
      • 1970-01-01
      • 2020-07-16
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2018-11-11
      • 2015-04-14
      相关资源
      最近更新 更多