react-native用户选择头像并保存本地

选择头像使用react-native-image-crop-picker
保存本地用@react-native-community/async-storage
下载使用跟正常插件一样,0.6以上版本不需要手动link

选择头像并将头像信息传给存储方法:

import ImagePicker from 'react-native-image-crop-picker';

ImagePicker.openPicker({
      width: 150,
      height: 200,
      cropping: true,
      cropperCircleOverlay: true,
    }).then(img => { //changeUserHeaderIcon 方法是父级组件传递的更改用户头像图片的方法
   		//img.path就是图片的地址,不过asyncStorage只能存储字符串形式数据还是要转换成字符串
      this.props.changeUserHeaderIcon(JSON.stringify({uri: img.path}));
    });

本地存储

import AsyncStorage from '@react-native-community/async-storage';

state = { // 默认的用户头像和默认的用户名
    userHeadIcon:require('../../assets/images/other/6.jpg'),
    userName:'Hello'
  }

componentDidMount = () => {
    this._retrieveData('userName')
    this._retrieveData('userHeadIcon')
  }
 //更改用户名
changeUserName=(userName)=>{
    this._storeData('userName',userName)
    this._retrieveData('userName')
  }
 //更改用户头像 
changeUserHeaderIcon = (image) => {
    this._storeData('userHeadIcon',image)
    this._retrieveData('userHeadIcon')
  }
//存储AsyncStorage
_storeData = async (key,value) => {
    try {
      console.log(key)
      console.log(value)
      await AsyncStorage.setItem(key, value);
    }
    catch (error) {
      console.log(error)
    }
  }
//获取AsyncStorage中信息并更改用户信息
  _retrieveData = async (key) => { 
    try {
      const value = await AsyncStorage.getItem(key);
      if (value !== null) {
        if(key == 'userName'){
          this.setState({userName:value})
        }else if(key== 'userHeadIcon'){
          this.setState({userHeadIcon:JSON.parse(value)})
        }
      }else{
        if(key == 'userName'){
          this.setState({userName:'Hello'})
        }else if(key== 'userHeadIcon'){
          this.setState({userHeadIcon:require('../../assets/images/other/6.jpg')})
        }
      }
     } catch (error) {
       console.log(error)
     }
  }
``

你可能感兴趣的:(react-native)