- React Native 教程
- React Native - 主页
- 核心概念
- React Native - 概述
- React Native - 环境设置
- React Native - 应用
- React Native - 状态
- React Native - 属性
- React Native - 样式
- React Native - Flexbox
- React Native - ListView
- React Native - 文本输入
- React Native - ScrollView
- React Native - 图片
- React Native - HTTP
- React Native - 按钮
- React Native - 动画
- React Native - 调试
- React Native - 路由
- React Native - 运行 iOS
- React Native - 运行 Android
- 组件和 API
- React Native - View
- React Native - WebView
- React Native - Modal
- React Native - ActivityIndicator
- React Native - Picker
- React Native - Status Bar
- React Native - Switch
- React Native - Text
- React Native - Alert
- React Native - 地理位置
- React Native - AsyncStorage
- React Native 实用资源
- React Native - 快速指南
- React Native - 实用资源
- React Native - 讨论
React Native - AsyncStorage
在本章中,我们将向您展示如何使用 AsyncStorage 保存数据。
第 1 步:演示
在此步骤中,我们将创建 App.js 文件。
import React from 'react' import AsyncStorageExample from './async_storage_example.js' const App = () => { return ( <AsyncStorageExample /> ) } export default App
第 2 步:逻辑
初始状态的 名称 为空字符串。组件装载时,我们将从持久性存储中对其进行更新。
setName 将从我们的输入字段获取文本,使用 AsyncStorage 存储文本,然后更新状态。
async_storage_example.js
import React, { Component } from 'react' import { StatusBar } from 'react-native' import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native' class AsyncStorageExample extends Component { state = { 'name': '' } componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value })) setName = (value) => { AsyncStorage.setItem('name', value); this.setState({ 'name': value }); } render() { return ( <View style = {styles.container}> <TextInput style = {styles.textInput} autoCapitalize = 'none' onChangeText = {this.setName}/> <Text> {this.state.name} </Text> </View> ) } } export default AsyncStorageExample const styles = StyleSheet.create ({ container: { flex: 1, alignItems: 'center', marginTop: 50 }, textInput: { margin: 5, height: 100, borderWidth: 1, backgroundColor: '#7685ed' } })
运行应用后,我们可以通过在输入字段中键入内容来更新文本。
广告