React Native:如何设置一个按钮,以处于其父母高度的70%的水平



假设我想将一个按钮定位在其父元素(即整个页面(中的30%的按钮中。如何使用Flexbox或其他方法执行此操作?

例如,如果我希望按钮是页面下方的50%,则将justifyContent: 'center'添加到父元素。

这是我的反应布局/样式表:

<View style={styles.container}>
  <LinearGradient colors={['#e80ca3', '#e500ff', '#950ce8']} style={styles.linearGradient}>
    <View style={styles.scanContainer}>
      <View style={styles.scanButton} />
    </View>
  </LinearGradient>
</View>
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  linearGradient: {
    flex: 1,
    alignSelf: 'stretch',
    justifyContent: 'center', // What to put here to make `scanContainer` 30% instead of 50% of the way down?
  },
  scanContainer: {
    alignSelf: 'center',
  },
  scanButton: {
    width: 175,
    height: 175,
    borderRadius: 87.5,
    backgroundColor: 'green',
  },
});

这是使用 flex properties

的解决方案
linearGradient: {
        flex: 1,
        alignSelf: 'stretch', //... Remove justifyContent: 'center',
    },
    scanContainer: {
        flex: 0.7,
        justifyContent: 'flex-end', // 30 % from the bottom
        alignSelf: 'center',
    },

您可以在按钮上方添加一个空的View,flex 0.7:

  <View style={{ flex: 1 }}>
    <View style={{ flex: 0.7 }} />
    <Button title="button" />
  </View>

您可以将absolute定位用于按钮容器。

scanContainer: {
  alignSelf: 'center',
  position: 'absolute',
  bottom: '30%',
  left: 0
}

使用flex:

<View style={[styles.scanContainer,{flex:1}]}>
   <View style={{flex:1}} />
   <View style={styles.scanButton} />
   <View style={{flex:2}} />
</View>

使用维度:

import {Dimensions} from 'react-native';
<View style={[styles.scanButton,{marginTop:Dimensions.get('window').height * 0.3}]} />

最新更新