我是一名RN萌新,以前是做安卓开发的,各种布局都非常的熟练,公司突然说要我学RN,我这一下转不过弯,我布局都写不出来。然后慢慢跟着别人的文章,然后一个个属性慢慢去试,但是先入为主,安卓布局的方式已经根深蒂固,我只能写这个笔记给自己看,到时候不记得的时候可以来翻一下。以下的内容纯属笔记,如有错误请大家斧正,谢谢。
import React from 'react';
import { View, Text,StyleSheet} from 'react-native';
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={myStyle.parent} >
<Text style={myStyle.childFirst}>按钮1</Text>
<Text style={myStyle.childSecond}>按钮2</Text>
<Text style={myStyle.childThird}>按钮3</Text>
</View>
)
};
}
const myStyle = StyleSheet.create({
parent: {
//flex 控制权重的,类似安卓里 LineaLayout 中的weight, 但是在这里有点不同,在RN当中,
//这个是表示充满父容器。如果是根节点,那么就会充满整个屏幕。
flex: 1,
//flexDirection 子集标签排列方向:
//flexDirection?: "row" | "column" | "row-reverse" | "column-reverse";
// row 是横向从左到右排列;column是竖向排从下到上列(系统默认);
//row-reverse 横向从有到左排列; column-reverse"竖向从下到上排列;
flexDirection:'row',
//backgroundColor 控制背景色,也可以用 red、green之类的代替。
backgroundColor : '#acacaf',
},
childFirst: {
backgroundColor: 'red',
//文字颜色 string
color: 'white',
//文字大小 number
fontSize: 14,
//所占比重 number
flex:2,
//外边距 number
margin: 5,
//控件宽度 number
width: 100,
//控件高度 number
height: 50,
//控制文本内容所在的位置
textAlign: 'center', //水平(X)居中
textAlignVertical: 'center', //垂直(Y)居中
//如果自己是父容器,控制子控件的位置,也是控制 居中(X,Y)的,具体哪个是哪个忘记了。
// justifyContent: 'center',
// alignItems: 'center',
},
childSecond: {
backgroundColor: 'green',
color: 'white',
// ...... 和childFirst 一样
},
childThird: {
backgroundColor: 'yellow',
color: '#000',
// ...... 和childFirst 一样
},
});
**上面的代码形成的是这么一个界面。由于根节点 flex: 1 ,所以根节点会充满这个屏幕, flexDirection:’row’,横向从左到右排列。第一和第二个按钮 flex: 2 ,第三个按钮flex: 1 ,就是前面两个按钮各占 2/5 ,第三个按钮 1/5 。 了解 flex 和 flexDirection 这两个属性之后,对于线性的布局就很快了。
这里再说下,自定义控件在使用的时候设置style没用,只有在定义的时候设置才有用。**
**上面的这种布局会形成这种样子的界面
justifyContent的布局样式和flexDirection有关,这里是flexDirection 是 row,是横向来的,如果是column就是竖向的,自己脑补想象竖着就好了。**