基于:https://reactnative.cn/docs/sample-application-movies/ 这个是RN中文网
刚学,啥都不懂,记录下。
1.安装环境时报了一些警告,然后项目运行时出了错。忘了具体什么错了。
解决就是坚持一下各个安装工具的版本,更新一些组件。
rn 命令行指定模拟器运行
1:查看模拟器列表:xcrun simctl list devices
2:运行:react-native run-ios --simulator "iPhone 7 Plus"
也可以XCode直接运行工程。
按示例运行时出现的问题:
表中提示没有key。
可以在数组中直接加上key属性,值必须唯一。
或者
default中添加
_keyExtractor = (item,index)=>item.id;
<SectionList
keyExtractor={this._keyExtractor}
/>
一些代码理解:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
Text,
Image,
StyleSheet,
FlatList,
View
} from 'react-native';
var REQUEST_URL =
"https://raw.githubusercontent.com/facebook/react-native/0.51-stable/docs/MoviesExample.json";
export default class AwesomeProject extends React.Component {//只能有一个default类,名字和工程名一致。
_keyExtractor = (item,index)=>item.id; //list里面itemkey使用
constructor(props){ //组件的声明
super(props); //先调用父类
this.state = { //这里面声明属性
data:[],
loaded:false,
};
// 在ES6中,如果在自定义的函数里使用了this关键字,则需要对其进行“绑定”操作,否则this的指向不对
// 像下面这行代码一样,在constructor中使用bind是其中一种做法(还有一些其他做法,如使用箭头函数等)
this.fetchData = this.fetchData.bind(this);
}
componentDidMount(){//componentDidMount是 React 组件的一个生命周期方法,它会在组件刚加载完成的时候调用一次,以后不会再被调用
this.fetchData();//调用fetch()方法
console.log("come in fetchData");
}
fetchData(){
fetch(REQUEST_URL)//请求url
.then((response)=>response.json())
.then((responseData)=>{
this.setState({
data:this.state.data.concat(responseData.movies),
loaded:true,
});
});
}
render(){//执行方法入口
if (!this.state.loaded) {
return this.renderLoadingView();
}
return(
<FlatList
keyExtractor={this._keyExtractor}
data={this.state.data}
renderItem={this.renderMovie}
style={styles.list}>
</FlatList>
);
// keyExtractor={this._extraUniqueKey}
// _extraUniqueKey(item,index){
// return "index"+index+item;
// }
}
renderLoadingView(){
return(
<View style={styles.container}>
<Text>
正在加载电影数据。。。。
</Text>
</View>
);
}
renderMovie({ item }){
return(
<View style={styles.container}>
<Image
source={{uri:item.posters.thumbnail}}
style={styles.thumbnail}
></Image>
<View style={styles.rightContainer}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.year}>{item.year}</Text>
</View>
</View>
);
}
}
//控件格式声明
var styles = StyleSheet.create({
container:{
flex:1,
flexDirection:'row',
justifyContent:'center',
alignItems:'center',
backgroundColor:'#F5FCFF',
},
thumbnail:{
width:53,
height:81
},
rightContainer:{
flex:1
},
title:{
fontSize:20,
marginBottom:8,
textAlign:'center',
},
year:{
textAlign:'center'
},
list:{
paddingTop:20,
backgroundColor:'#F5FCFF',
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);