如何在React Native中单击按钮打开文档选择器

时间:2018-10-07 13:42:18

标签: react-native react-native-android document-types

我已经尝试过使用此链接(https://www.npmjs.com/package/react-native-document-picker)中给出的相同方法,但是它会在表单加载本身上打开文档选择器。

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button} from 'react-native';
import { DocumentPicker, DocumentPickerUtil } from 'react-native-document-picker';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends Component<Props> {

  TryUploadFile = () => {

    DocumentPicker.show({
      filetype: [DocumentPickerUtil.images()],
    },(error,res) => {
      // Android
      console.log(
         res.uri,
         res.type, // mime type
         res.fileName,
         res.fileSize
      );
    });

  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
        <Button title="Upload File" onPress={this.TryUploadFile()}/>
      </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,
  },
});

但是在加载应用程序时它正在加载文档选择器,并且可见。

1 个答案:

答案 0 :(得分:1)

在按钮上将此onPress={this.TryUploadFile()}更改为onPress={this.TryUploadFile}