react-native - Flex box 不会导致本机反应?
问题描述
我正在使用 flex-box 设计反应原生应用程序的 UI。但是它的代码没有显示预期的结果?
问题
Margin 属性InnerContainer2
没有margin:'5%'
垂直覆盖相等的空间。
代码:
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.innerContainer1}>
<View style={styles.innerContainer2}>
<Text style={styles.welcome}>This is live reload</Text>
</View>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'grey'
},
innerContainer1: {
flex: 1,
width: '80%',
margin: '10%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'lightgrey'
},
innerContainer2: {
flex: 1,
width: '80%',
margin: '5%',
height: 'auto',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'grey'
},
welcome: {
textAlign: 'center',
margin: 10,
}
});
预期产出
实际输出
解决方案
好的,有两件事:
1) Margin/Padding 不能很好地与“百分比值”配合使用,因为它会干扰其他组件的高度和宽度。因此,请始终使用确切的值。如果您担心其他屏幕尺寸,那么您可以使用尺寸库来计算任何屏幕的确切宽度和高度,并从那里分配一个边距。
2) 当您必须为父元素内的两个组件分配比率时,通常使用 Flex。此示例将使子组件占其父元素的 50%。
例如:
父组件 => flex: 1
子(A)组件 => 弹性:0.5
子(B)组件 => 弹性:0.5
除了我对你的风格类做了一些调整。它按预期工作。希望你能理解或者你可以问我:)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'grey',
},
innerContainer1: {
// flex: 1, used when you have to assign a ratio for two components inside a parent element
width: '80%',
height: '80%',
margin: 10,
justifyContent: 'center',
// alignItems: 'center', It gives the desired result when used in the parent component.
backgroundColor: 'lightgrey',
},
innerContainer2: {
// flex: 1, used when you have to assign a ratio for two components inside a parent element.
width: '80%',
margin: 30,
height: '80%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
},
welcome: {
textAlign: 'center',
margin: 10,
},
});
参考:
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
推荐阅读
- angular - 将参数从.net dll(或控制台应用程序)传递到角度应用程序(角度 5)
- javascript - 在旧的基础上初始化一个新的 highcharts 对象
- javascript - Bootstrap导航栏下拉菜单和汉堡不起作用
- android - MPAndroidChart:XAxisValueFormatter 中的 ArrayIndexOutOfBoundsException
- hadoop - Hadoop 3.1.1 启动 HDFS 服务的问题
- java - 是否可以从客户端公钥中提取信息以便在服务器上创建唯一文件夹?
- sql - Sql 查询查找只有一行的行(用于 exp 许可证)
- python - 将numpy字符串数组转换为日期时间
- sql-server-2016 - 使用 Entity Framework Core 2.1 插入时态表时出错
- android - 更改材质组件样式属性失败