使用react-native-image-picker在react-native中上传图像

时间:2017-06-05 14:12:28

标签: reactjs react-native react-native-android

我刚刚初始化了一个基本的react-native项目,并在模拟器中运行。我已经安装了这个包https://github.com/react-community/react-native-image-picker

我试图上传图片。代码很简单,因为我刚刚添加了一些代码来处理图像上传

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Button,
  Text,
  Image,
  Alert,
  View
} from 'react-native';


var ImagePicker = require('react-native-image-picker');

var options = {
  title: 'Select Avatar',
  customButtons: [
    {name: 'fb', title: 'Choose Photo from Facebook'},
  ],
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};


const onPressLearnMore = () => { 

ImagePicker.launchImageLibrary(options, (response)  => {

let source = { uri: response.uri };

    this.setState({
      avatarSource: source
    });

});

//Alert.alert('Button has been pressed!');
};

export default class AwesomeProject extends Component {
    constructor() {
      super()
      this.state = {
         avatarSource: 'image.jpg'
      }
   }

  render() {
    return (

      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Button onPress={onPressLearnMore} title="Upload Image" color="#841584" accessibilityLabel="Learn more about this purple button" />

        <Image source={this.state.avatarSource} style={styles.uploadAvatar} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

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

我在模拟器上运行时出现此错误

undefined is not a function (evaluating '_this.setState({
      avatarSource: source
    })')
<unknown>
    index.android.bundle?platform=android&dev=true&hot=false&minify=false:1274:19
__invokeCallback
    index.android.bundle?platform=android&dev=true&hot=false&minify=false:4818:21
<unknown>
    index.android.bundle?platform=android&dev=true&hot=false&minify=false:4664:32
__guard
    index.android.bundle?platform=android&dev=true&hot=false&minify=false:4753:11
invokeCallbackAndReturnFlushedQueue
    index.android.bundle?platform=android&dev=true&hot=false&minify=false:4663:19

1 个答案:

答案 0 :(得分:0)

您应该在AwesomeProject组件中编写onPressLearnMore函数,并且不要忘记绑定以使用this

export default class AwesomeProject extends Component {
  constructor(){
    ...
    this.onPressLearnMore = this.onPressLearnMore.bind(this)
  }

  onPressLearnMore(){
  //you can use this.setState
  }


  render(){
  ...
  }
}