React Native学习(5)组件的高度与宽度
指定宽高
就是直接赋予组件width和height,React Native 中的尺寸都是无单位的,表示的是与设备像素密度无关的逻辑像素点。
/**
* 慢慢学习
* https://blog.csdn.net/quanhaoH
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class MyApp extends Component {
render() {
return (
<View>
<View style={styles.red} />
<View style={styles.bigBlue} />
<View style={styles.black} />
</View>
);
}
}
const styles = StyleSheet.create({
red: {
width: 50,
height: 50,
backgroundColor: 'red',
},
bigBlue: {
width: 100,
height: 100,
backgroundColor: 'blue',
},
black: {
width: 150,
height: 150,
backgroundColor: 'black',
},
});
AppRegistry.registerComponent('MyApp', () => MyApp);
这样给组件设置尺寸也是一种常见的模式,比如要求在不同尺寸的屏幕上都显示成一样的大小。
弹性(Flex)宽高
在组件样式中使用flex可以使其在可利用的空间中动态地扩张或收缩。一般而言我们会使用flex:1来指定某个组件扩张以撑满所有剩余的空间。则这些子组件会平分父容器中剩余的空间。如果这些并列的子组件的flex值不一样,则谁的值更大,谁占据剩余空间的比例就更大。
如:
/**
* 慢慢学习
* https://blog.csdn.net/quanhaoH
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class MyApp extends Component {
render() {
return (
<View style={{flex: 1}}>
<View style={styles.red} />
<View style={styles.bigBlue} />
<View style={styles.black} />
</View>
);
}
}
const styles = StyleSheet.create({
red: {
flex: 1,
width: 50,
height: 50,
backgroundColor: 'red',
},
bigBlue: {
flex: 2,
width: 100,
height: 100,
backgroundColor: 'blue',
},
black: {
flex: 13,
width: 150,
height: 150,
backgroundColor: 'black',
},
});
AppRegistry.registerComponent('MyApp', () => MyApp);
组件能够撑满剩余空间的前提是其父容器的尺寸不为零。如果父容器既没有固定的width和height,也没有设定flex,则父容器的尺寸为零。其子组件如果使用了flex,也是无法显示的。
比如这样父视图尺寸为0。子组件还使用了flex,则子组件就无法显示了
<View>
<View style={styles.red} />
<View style={styles.bigBlue} />
<View style={styles.black} />
</View>
父视图使用指定宽高也是可以的
如:
/**
* 慢慢学习
* https://blog.csdn.net/quanhaoH
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class MyApp extends Component {
render() {
return (
<View style={{width:300, height:400, backgroundColor: 'yellow'}}>
<View style={styles.red} />
<View style={styles.bigBlue} />
<View style={styles.black} />
</View>
);
}
}
const styles = StyleSheet.create({
red: {
flex: 1,
width: 50,
height: 50,
backgroundColor: 'red',
},
bigBlue: {
flex: 2,
width: 100,
height: 100,
backgroundColor: 'blue',
},
black: {
flex: 13,
width: 150,
height: 150,
backgroundColor: 'black',
},
});
AppRegistry.registerComponent('MyApp', () => MyApp);