一、代码
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.doXMLHttpRequest.bind(this)}>获取数据</Text> 25 <Text>{this.state.responseText}</Text> 26 </View> 27 ); 28 } 29 30 //使用XMLHttpRequest请求数据 31 doXMLHttpRequest(){ 32 var request = new XMLHttpRequest(); 33 request.onreadystatechange = (e) => { 34 if (request.readyState !== 4) { 35 return; 36 } 37 38 if (request.status === 200) { 39 alert("请求成功!"); 40 this.setState({responseText: request.responseText}) 41 console.log(request.responseText); 42 43 } else { 44 alert("请求失败!"); 45 } 46 }; 47 48 request.open('GET', 'https://httpbin.org/get'); 49 request.send(); 50 } 51 } 52 53 //样式定义 54 const styles = StyleSheet.create({ 55 container:{ 56 flex: 1, 57 marginTop:25 58 }, 59 item:{ 60 margin:15, 61 height:30, 62 borderWidth:1, 63 padding:6, 64 borderColor:'#ddd', 65 textAlign:'center' 66 }, 67 });
二、效果图
点关注各类It学习资源免费送+V 1153553800