一、代码
1 import React, { Component } from 'react'; 2 import { 3 AppRegistry, 4 StyleSheet, 5 Text, 6 View 7 } from 'react-native'; 8 9 //默认应用的容器组件 10 export default class App extends Component { 11 12 //构造函数 13 constructor(props) { 14 super(props); 15 this.state = { 16 responseText: null 17 }; 18 } 19 20 //渲染 21 render() { 22 return ( 23 <View style={styles.container}> 24 <Text style={styles.item} onPress={this.doFetch.bind(this)}>获取数据</Text> 25 <Text>{this.state.responseText}</Text> 26 </View> 27 ); 28 } 29 30 //使用Fetch请求数据 31 doFetch(){ 32 fetch('https://httpbin.org/get') 33 .then(function(data){ 34 return data.text(); 35 }) 36 .then((responseText) => { 37 alert("请求成功!"); 38 this.setState({responseText}) 39 console.log(responseText); 40 }) 41 .catch((error) => { 42 alert("请求失败!"); 43 }); 44 } 45 } 46 47 //样式定义 48 const styles = StyleSheet.create({ 49 container:{ 50 flex: 1, 51 marginTop:25 52 }, 53 item:{ 54 margin:15, 55 height:30, 56 borderWidth:1, 57 padding:6, 58 borderColor:'#ddd', 59 textAlign:'center' 60 }, 61 });
二、效果图