首页 > 解决方案 > 保持组件底部到顶部组件的 50%

问题描述

我正在尝试制作个人资料页面 ui,其中名称和生物容器等个人资料数据将保持 50% 到其顶部组件的底部,即现在的封面图片。

这是我的 React Native 代码,

<View style={styles.container}>
        <View style={styles.coverContainer}>

        </View>
        <View style={styles.profileDataContainer}>

        </View>
        <View style={styles.intrestsContainer}>

        </View>
        <View style={styles.topicsContainer}>

        </View>
      </View>

而现在的款式,

const styles = StyleSheet.create({
  container: {

  },
  coverContainer: {
      height : 200,
      backgroundColor : 'blue'
  },
  profileDataContainer: {
      marginHorizontal : 30,
      backgroundColor: 'white',
      height : 200,
      shadowColor: "#e5e5e5",
      shadowOffset: {
        width: 0,
        height: 2
      },
      shadowRadius: 2,
      shadowOpacity: 1.0,
      elevation : 4,
      marginTop : -100,
  }

});

我添加了marginTop:-100 使其看起来像我想要的结构。

截屏

所以这就是在将 marginTop 添加到 -100 后现在的样子,但这不是响应式的,当我增加那个白色块的大小时。它不再停留在中心位置。

需要有关如何做到这一点的帮助:(

标签: cssreactjsreact-native

解决方案


您可以使用百分比而不是逻辑像素来执行此操作,如下例所示:

const WindowHeight = Dimensions.get('window').height;

export default class App extends Component {

  render() {
    return (
      <View style={styles.container}>
      <View style={styles.headerBackground}/>
      <View style={styles.header}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'grey',
  },
  headerBackground: {
    height: '30%',
    width: '100%',
    backgroundColor : 'blue'
  },
  header: {
    height: '30%',
    width: '80%',
    marginTop: WindowHeight * -0.15,
    backgroundColor : 'white'
  }
});

在此示例中,我将蓝色背景和白色标题的高度设置为窗口高度的 30%,将 marginTop 设置为窗口高度的 -15%(我必须使用尺寸,因为如果我使用百分比,它将是宽度的百分比...

您可以在零食上运行我的示例:https ://snack.expo.io/Hyd7ChplX


推荐阅读