React Native : AsyncStorage 存儲

React Native 初探 : https://my.oschina.net/letiantian/blog/753841html

AsyncStorage 的介紹見: http://reactnative.cn/docs/next/asyncstorage.html
這是一個kv存儲,key和value都是字符串。固然value可使用字符串形式的xml、json等。react

這裏順便試用下 https://github.com/larsvinter/react-native-awesome-button 和ToastAndroid。git

npm install react-native-awesome-button --save

代碼

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  View,
  AsyncStorage,
  ToastAndroid
} from 'react-native';

import AwesomeButton from 'react-native-awesome-button';

const KEY = 'name';


const styles = StyleSheet.create({
  container: {
    // flex: 1,
    // flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    margin: 20,
    backgroundColor: '#F5FCFF',
  },
  buttonBackground: {
    height: 40,
    width: 200,
    borderRadius: 5,
    margin: 20
  },
});


class MyReactNativeProject extends Component {

  _setValue() {
    console.log('set value');
    AsyncStorage.setItem(KEY, 'letian', (err, result) => {
      console.log('set: err?', err, '; result?', result);
      if (err) {
        ToastAndroid.show('set發生錯誤', ToastAndroid.SHORT);
      }
      else {
        ToastAndroid.show('成功set', ToastAndroid.SHORT);
      }
    });
  }

  _getValue() {
    console.log('get value');
    AsyncStorage.getItem(KEY).then((value) => {
      console.log('value is: ', value);
      ToastAndroid.show('value is ' + value, ToastAndroid.SHORT)
    });
  }

  render() {

    return (
      <View style={styles.container}>

        <AwesomeButton 
            backgroundStyle={styles.buttonBackground}
            states={{
                default: {
                  text: 'set',
                  onPress: this._setValue,
                  backgroundColor: '#1155DD'
                }
              }}
        />
        <AwesomeButton 
            backgroundStyle={styles.buttonBackground}
            states={{
                default: {
                  text: '取',
                  onPress: this._getValue,
                  backgroundColor: '#1155DD'
                }
              }}
        />
      </View>
    );
  }
}



AppRegistry.registerComponent('MyReactNativeProject', () => MyReactNativeProject);

效果圖

相關文章
相關標籤/搜索