一、代码
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native'; //默认应用的容器组件
export default class App extends Component { //构造函数
constructor(props) {
super(props);
this.state = {
responseText: null
};
} //渲染
render() {
return (
<View style={styles.container}>
<Text style={styles.item} onPress={this.doXMLHttpRequest.bind(this)}>获取数据</Text>
<Text>{this.state.responseText}</Text>
</View>
);
} //使用XMLHttpRequest请求数据
doXMLHttpRequest(){
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
} if (request.status === 200) {
alert("请求成功!");
this.setState({responseText: request.responseText})
console.log(request.responseText); } else {
alert("请求失败!");
}
}; request.open('GET', 'https://httpbin.org/get');
request.send();
}
} //样式定义
const styles = StyleSheet.create({
container:{
flex: 1,
marginTop:25
},
item:{
margin:15,
height:30,
borderWidth:1,
padding:6,
borderColor:'#ddd',
textAlign:'center'
},
});
二、效果图