/*** Created by Bfire on 2017/11/22.*/'use strict';import React, {Component} from "react";import {ActivityIndicator, Animated, FlatList, ScrollView, StyleSheet, Text, TextInput, Button, View, Alert} from "react-native";const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);const REQUEST_URL = 'https://api.github.com/search/repositories?sort=stars&q=';let that;class FlatListExample extends Component { static navigationOptions = { title: 'FlatListExample', } constructor(props) { super(props); this.state = { isLoading: true, //网络请求状态 error: false, errorInfo: "", dataArray: [], txt: "", }; that = this; } //网络请求 fetchData() { let txt = this.state.txt ? this.state.txt : 'javascript'; let url = REQUEST_URL + txt; //这个是js的访问网络的方法 fetch(url) .then((response) => response.json()) .then((responseData) => { let data = responseData.items; let dataBlob = []; let i = 0; data.map(function (item) { dataBlob.push({ key: i, value: item, }) i++; }); this.setState({ //复制数据源 dataArray: dataBlob, isLoading: false, }); data = null; dataBlob = null; }) .catch((error) => { this.setState({ error: true, errorInfo: error }) }) .done(); } componentDidMount() { //请求数据 this.fetchData(); } onButtonPress(txt){ //Alert.alert('点击了查询'+that.state.txt); //请求数据 that.fetchData(); } //加载等待的view renderLoadingView() { return ( <View style={styles.container}> <ActivityIndicator animating={true} style={[styles.gray, {height: 80}]} color='red' size="large" /> </View> ); } //加载失败view renderErrorView(error) { return ( <View style={styles.container}> <Text> Fail: {error} </Text> </View> ); } //返回itemView renderItemView({item}) { return ( <View> <Text style={styles.title}>name: {item.value.name} ({item.value.stargazers_count} stars)</Text> <Text style={styles.content}>description: {item.value.description}</Text> </View> ); } renderData() { return ( <ScrollView > <Text > This is React native test </Text> <TextInput style={{height: 40}} placeholder="请输入你要查询的项目名称!" onChangeText={(text) => this.setState({txt:text})} /> <Button onPress={this.onButtonPress} title="查询" color="#841584" /> <Text > Most popular {this.state.txt} projects In github </Text> <Text > Data: </Text> <AnimatedFlatList data={this.state.dataArray} renderItem={this.renderItemView} /> </ScrollView> ); } render() { //第一次加载等待的view if (this.state.isLoading && !this.state.error) { return this.renderLoadingView(); } else if (this.state.error) { //请求失败view return this.renderErrorView(this.state.errorInfo); } //加载数据 return this.renderData(); }}const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, title: { fontSize: 15, color: 'blue', }, content: { fontSize: 15, color: 'black', }, textInput: { fontSize: 16, height: 40 }, inputLayout: { marginTop: 16, marginHorizontal: 36 }});module.exports = FlatListExample;