我正在尝试在我的 React Native 元素上使用边距样式属性的百分比值,但它似乎降低了我的 View 组件之一的高度。如果我用绝对值替换百分比值,就没有问题了,它工作正常。您是否尝试在 React Native 中使用百分比值作为边距?以下是重现此问题的一些代码示例:
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.scene}>
<View style={styles.card}>
<View style={styles.container}>
<Text>Hello World</Text>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
scene: {
backgroundColor: '#F9E8D5',
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
flexDirection: 'column'
},
card: {
backgroundColor: '#E6D5C3',
flex: 0.2,
flexDirection: 'column',
marginTop: '20%' // Replace by 20
},
container: {
backgroundColor: '#FFFFFF',
flex: 1,
flexDirection: 'column',
justifyContent: 'center'
}
});
非常感谢!
最佳答案
组件的高度和宽度决定了它在屏幕上的大小。
设置组件尺寸的最简单方法是为样式添加固定的宽度和高度。 React Native 中的所有维度都是无单位的,并且表示与密度无关的像素。
以这种方式设置尺寸对于无论屏幕尺寸如何都应始终以完全相同的尺寸呈现的组件来说很常见。
在组件样式中使用 flex 可以让组件根据可用空间动态扩展和收缩。通常你会使用 flex: 1。
以下引用将用于样式
https://facebook.github.io/react-native/docs/height-and-width.html
https://medium.com/the-react-native-log/tips-for-styling-your-react-native-apps-3f61608655eb
https://facebook.github.io/react-native/docs/layout-props.html#paddingtop
使用Dimensions计算得到屏幕的高和宽。
var {height, width} = Dimensions.get('window');
通过获取屏幕大小并转换为百分比来指定百分比。
示例:
const { height } = Dimensions.get('window'); paddingTop: height * 0.1 // 10 percentage of the screen height
关于css - React-Native:带百分比值的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50485622/