介绍完了react native的属性、组件、状态、样式后,很多开发者会问怎么做一些网路的交互工作呢?
看完本小节,你就知道怎么开发一些网络交互的操作了。
通过网络获取数据的代码如下,写的有点乱。。。但是可以用。。。。。。
import React from 'react'; import React from 'react'; import { StyleSheet, Text, View, Image } from 'react-native'; class BlinkText extends React.Component { constructor(props) { super(props); this.state = { showText: true, movieText: ""}; // 每1000毫秒对showText状态做一次取反操作 setInterval(() => { this.setState(previousState => { this.getMoviesFromApi(); return { showText: !previousState.showText }; }); }, 1000); } async getMoviesFromApi() { try { // 注意这里的await语句,其所在的函数必须有async关键字声明 let response = await fetch('https://facebook.github.io/react-native/movies.json'); let responseJson = await response.json(); this.state.movieText = responseJson.movies[0].title; } catch(error) { console.error(error); } } render() { // 根据当前showText的值决定是否显示text内容 let display = this.state.showText ? this.props.text : ' '; let movieText = this.state.movieText; return ( <Text style={fontStyles.bigblue}>{movieText}</Text> ); } } export default class App extends React.Component { render() { let pic = { uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' }; return ( <View style={styles.container}> <BlinkText text="fashici"/> <BlinkText text="my friend"/> <Text>Shake your phone to open the developer menu.</Text> <Image source={pic} style={{width: 193, height: 110}} /> </View> ); } } const fontStyles = StyleSheet.create({ bigblue: { color: 'blue', fontWeight: 'bold', fontSize: 30, }, red: { color: 'red', }, }); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
网址https://facebook.github.io/react-native/movies.json的内容为:
{ "title": "The Basics - Networking", "description": "Your app fetched this from a remote endpoint!", "movies": [ { "title": "Star Wars", "releaseYear": "1977"}, { "title": "Back to the Future", "releaseYear": "1985"}, { "title": "The Matrix", "releaseYear": "1999"}, { "title": "Inception", "releaseYear": "2010"}, { "title": "Interstellar", "releaseYear": "2014"} ] }
效果如下:
参考:
http://blog.csdn.net/u012620506/article/details/52346264