React Native开发:
一:ReactNative项目创建及结构分析
命令行终端创建工程
(1) cd 文件夹路径地址 回车
(2) react-native init HelloWorld 回车
项目创建完成后,在文件夹中会有一些自动生成的文件:android,ios文件夹,index.ios(android).js等...打开index.ios.js,里面有一些代码:
/*
第一部分
导入ReactNative包,导入ReactNative组件
AppRegistry:JS运行所有ReactNative应用的入口
StyleSheet:ReactNative使用的样式表,类似CSS样式表
各种开发中需要使用的组件
模板中使用的是ES6语法,ES5语法如下:
let React = require("react-native");
let {
AppRegistry,
StyleSheet,
Text,
View
} = React;
require函数,搜索目录加载文件
*/
/*
第二部分
创建ReactNative组件
模板中使用的是ES6语法
render() {} 是WS6中的函数简写
ES5语法如下:
var HellWorld = React.creatClass({
render: function(){
return {};
}
});
*/
/*
第三部分
StyleSheet.creat创建样式实例
在应用中只会被创建一次,不用每次在渲染周期中重新创建
*/
/*
第四部分
注册入口组件
APPRegistry:负责注册运行ReactNative应用程序的JavaScript入口
registerComponent注册应用程序的入口组件,告知ReactNativa哪一个组件被注册为应用的根容器
第二个参数使用了ES6语法,箭头函数:
{} =>HelloWorld
返回的必须是定义的组件类的名字
等价于
function() {return HelloWorld}
*/
调出调试工具:cmd+d
二:StyleSheet
eg:View包括两个View
//定义组件
//拼接样式中,数组中居后的优先级高
var LessonStyle = React.creatClass({
render: function() {
return (
<View style={styles.container}>
<View style={[styles.top,styles.border]}>
</View>
<View style={[styles.bottom,styles.border]}>
</View>
</View>
);
}
});
//定义样式
var style = StyleSheet.create({
//外层View
container: {
marginTop:25,
marginLeft:30,
backgroundColor: "red",
width:300,
height:400,
},
//上层View
top: {
background:"green",
width:280,
height:250,
margin:10,
},
//下层View
bottom:{
background:"yellow",
width:280,
height:110,
margin:10,
},
border:{
borderWidth:3,
borderColor:"black",
}
});
三:Flexbox
w3cSchool:CSS3弹性盒子
eg:
var LessonFlex = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.child1}>
</View>
<View style={styles.child2}>
</View>
</View>
);
}
});
var style = StyleSheet.create({
container: {
margin:30,
width:300,
height:500,
backgroundColor: "yellow",
//默认主轴方向是column
//设置为横向排列
flexDirection:"row",
//主轴方向
justifyContent:"center",
//交叉轴
alignItem:"center",
},
child1: {
width:100,
height:100,
backgroundColor:"green",
},
child2:{
width:100,
height:100,
backgroundColor:"blue"
}
});
/*
flex属性
可以给组件指定flex,flex的值是数字,flex:1表示,组件可以撑满父组件所有的剩余空间
同时存在多个并列的子组件,flex:1,均分
如果这些并列的子组件的flex值不一样,则谁的值更大,谁占据剩余空间的比例就更大(即占据剩余空间的比等于并列组件间flex值的比)
*/
eg:
var styles = StyleSheet.creat({
container: {
margin:30,
flex:1,
backgroundColor:"cyan",
},
child1: {
flex:1,
backgroundColor:"green",
},
child2: {
flex:1,
backgroundColor:"yellow",
}
});