React Native 学习
离职后把之前落下的课程补起来,多花时间在“道”上,少花时间在“术"上。
基础原理、设计模式继续搞起来
文章目录
介绍
用React开发原生应用的框架
环境搭建
官网
模拟器: 夜神、MuMu
基础知识
React 知识必备
数据
- this.state 初始化数据,类似 vue 的 data
- this.setState 更新数据,eg:
this.setState({title: '新标题'})
基础组件
- View——div
- Text——span 文本必须用Text包裹
- Image——image source={{uri: imgurl}} 网络图片需要设置宽高,本地路径用require引用
- ScrollView 滚动组件,onScroll 事件
- TextInput——input value={this.state.title}绑定数据,
onChangeText={(value) => this.setState({title: value})}双向绑定 - Alert——是api,不是组件,Alert.alert() 方法弹框
- FlatList 可是区域加载数据,节流,类似 ScrollView 的滚动加载
- ActivityIndicator 加载icon
样式
- 驼峰命名
- 大小不需要单位
- 无复合样式,eg:background,没有简写,只能一个个写样式
- 所有元素都是 flex 布局,默认
- 宽高百分百,只能通过
Dimensions获取
const styles = StyleSheet.create({
container: {
width: Dimensions.get('window').width, // 获取设备宽度,=100%
height: Dimension.get('window').height
marginBottom: 10,
padding: 10
}
})
paddingHorizontalmarginHorizontal可以设置水平方向两个属性paddingVerticalmarginVertical可以设置垂直方向两个属性
布局
flex
默认是 column 方向,父容器要设置宽高,否则子元素 flex 属性无效,不设置宽高,flex 的父元素宽高为 0
- flexDirection 设置主轴方向
- jusitifyContent 主轴方向布局设置
- alignItems 交叉轴方向
请求数据
- fetch (推荐)
- XMLHttpRequest
fetch(url)
.then(response => response.json()) // response的原始数据
.then(resp => console.log(resp)) // 返回的json数据,在这里使用
- 返回 json 数据用 json 方法
- text() 方法返回 text
遇到 ‘response body is locked’ 问题,可以这样解决, response.clone().json()
请求带参数
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json;chartset=UTF-8"
},
body: JSON.stringify({key:123, search:"hello"})
})
.then(response => response.json()) // response的原始数据
.then(resp => console.log(resp)) // 返回的json数据,在这里使用
第三方插件
swiper 轮播
- 可以自己实现,用 ScrollView
- react-native-swiper, 需要用的时候看官方文档
react-navigation 页面导航切换
createBottomTabNavigator 底部tabbar
若通过组件导出,需要放到
App.jsrender 的作为根组件
eg:
import BottomTabbar from './BottomTabbar'
...
render() {
return (
<BottomTabbar />
)
}
小结
入门难度不难,环境配置有点烦,如要进步快,还得来项目。
2935



被折叠的 条评论
为什么被折叠?



