首页 > 解决方案 > 如何从反应本机表单中输入字段旁边的按钮选择文件。(请参阅图片以更好地理解)

问题描述

我是新来的反应本地人。我创建了一个表格。现在在该表单中,我想要输入字段旁边的选择文件按钮。当用户点击选择文件按钮时。相机将打开或画廊将打开(根据用户选择),然后当用户单击选择文件按钮时,选择文件按钮下方出现一个小图像或只是图像名称

这是我的图片以便更好地理解 在此处输入图像描述

这是我的代码

import React, {useState, Component} from 'react';
import {Picker, Text, StyleSheet, View,
   TextInput, Button, KeyboardAvoidingView,
    ScrollView, Alert, alert, TouchableOpacity, Dimensions,} from 'react-native';
import { StackNavigator, navigation} from "react-navigation";
import { Card, Badge, Block, } from "../components";
import { theme, mocks } from "../constants";
import DigSign from "./DigSign"
import { Ionicons } from '@expo/vector-icons';

const { height } = Dimensions.get("window");
const { width } = Dimensions.get("window");


class PickerDemo extends Component{
    

  constructor(props) {
    super(props);
    this.state={
    };
  }
  

  validateInputs = () => {
  //  if (!this.state.accountNo.trim()) 
  if (!/[A-Z]{5}[0-9]{4}[A-Z]{1}/.test(this.state.PAN))
  {
    this.setState({ PANError: 'Please enter valid PAN Number' })
    return;
  }
  if (!/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/.test(this.state.GST)) 
  {
    this.setState({ GSTError: 'Please enter valid GST Number' })
    return;
  }
  if (!/^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$/.test(this.state.Aadhar)) 
  {
    this.setState({ AadharError: 'Please enter valid Aadhar Number' })
    return;
  }
    else {
      Alert.alert("All fields validated")
      return;
    }
  }

  handlePAN = (text) => {
    this.setState({ PANError: '' })
    this.setState({ PAN: text })
  }
  handleGST = (text) => {
    this.setState({ GSTError: '' })
    this.setState({ GST: text })
  }
  handleAadhar = (text) => {
    this.setState({ AadharError: '' })
    this.setState({ Aadhar: text })
  }

render(){
  const offset = (Platform.OS === 'android') ? -200 : 0;
  const { navigation } = this.props;


  return (
    <View style={{flex: 1}}>

      <View style={styles.header}>
       <Ionicons style={{paddingLeft:20}} name="arrow-back" size={40} 
      color="black"  onPress={() => navigation.navigate("FormItems")} />
      <Text style={{fontSize:20, paddingLeft: 70, paddingTop: 10}}>KYC Details</Text>
      </View>

    <KeyboardAvoidingView keyboardVerticalOffset={offset} style={styles.form} behavior='padding'>

      

      <Text style={styles.formLabel}> OTHER INFORMATION Form </Text>
      <ScrollView style={{flex: 1,}} showsVerticalScrollIndicator={false}>   

      <View style={{flexDirection:'row'}}>    
      <TextInput maxLength={30} placeholder="PAN Card Number *" style={styles.inputStyle}
       onChangeText={this.handlePAN} />
       <View style={{justifyContent:"center"}}>
        <Button title={'Choose File'}/>
        </View>
        </View>
        <Text>{this.state.PANError}</Text>

        <View style={{flexDirection:'row'}}> 
        <TextInput maxLength={30}  placeholder="GSTIN Number*" style={styles.inputStyle}
         onChangeText={this.handleGST} />
        <View style={{justifyContent:"center"}}>
        <Button title={'Choose File'}/>
        </View>
        </View>
        <Text>{this.state.GSTError}</Text>

        <View style={{flexDirection:'row'}}> 
        <TextInput maxLength={30} placeholder="Aadhar Card Number*" style={styles.inputStyle}
         onChangeText={this.handleAadhar} />
        <View style={{justifyContent:"center"}}>
        <Button title={'Choose File'}/>
        </View>
        </View>
        <Text>{this.state.AadharError}</Text>

          <TouchableOpacity
         onPress={() => navigation.navigate("DigSign")}
       >
         <Card center middle shadow style={styles.category}>
           <Text medium height={1} size={1}>
             Digital Signature
           </Text>
         </Card>
       </TouchableOpacity>
       
       <TouchableOpacity
         onPress={() => navigation.navigate("ImgpickWithCam")}
       >
         <Card center middle shadow style={styles.category}>
           <Text medium height={1} size={1}>
             Pick An Image From Camera
           </Text>
         </Card>
       </TouchableOpacity>
          
        </ScrollView>
          
        
        <View style={{ height: 30 }} />
        <Button style={styles.inputStyleB}
          title="Submit"
          color="#808080"
          onPress={() => this.validateInputs()}
        />
        </KeyboardAvoidingView>
        </View>


  );
};
}

const styles = StyleSheet.create({
    form: {
        flex: 1,
        justifyContent: "center",
        flex: 1,
        backgroundColor: "rgb(247, 146, 57)",
        alignItems: 'center',
        paddingTop: 50,
      },
  container: {
    flex: 1,
    backgroundColor: "rgb(247, 146, 57)",
    alignItems: 'center',
    // justifyContent: 'center',
    paddingTop: 15
  },

  formLabel: {
    fontSize: 20,
    color: 'rgb(10, 10, 10)',
  },
  inputStyle: {
    marginTop: 20,
    width: 220,
    height: 40,
    paddingHorizontal: 10,
    borderRadius: 50,
    backgroundColor: 'rgb(255, 252, 252)',
  },
  formText: {
    alignItems: 'center',
    justifyContent: 'center',
    color: '#fff',
    fontSize: 20,
  },
  text: {
    color: '#fff',
    fontSize: 20,
  },
 
  category: {
    marginTop: 20,
    
        // this should be dynamic based on screen width
    minWidth: (width - theme.sizes.padding * -10 - theme.sizes.base) / 2,
    maxWidth: (width - theme.sizes.padding * -10 - theme.sizes.base) / 2,
    maxHeight: (height - theme.sizes.padding * -50 - theme.sizes.base) / 2,
  },
  header:{
    flexDirection: 'row'
  }
});

export default PickerDemo;

标签: react-native

解决方案


这是基于我给您的前面示例的解决方案。

您只需要对其进行条件渲染。

只需要几行代码:)

工作示例:世博小吃

在此处输入图像描述

import React, { useState, useEffect } from 'react';
import {
  StyleSheet,
  View,
  Button,
  Image,
  FlatList,
  Text,
  TextInput,
} from 'react-native';
import { Camera } from 'expo-camera';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';

export default function Add() {
  const [cameraPermission, setCameraPermission] = useState(null);
  const [galleryPermission, setGalleryPermission] = useState(null);
  const [showCamera, setShowCamera] = useState(false);

  const [camera, setCamera] = useState(null);
  const [imageUri, setImageUri] = useState([]);
  const [type, setType] = useState(Camera.Constants.Type.back);
  const [imageArray, setImageArray] = useState([]);

  const permisionFunction = async () => {
    // here is how you can get the camera permission
    const cameraPermission = await Camera.requestPermissionsAsync();
    console.log('camera permission:', cameraPermission.status);

    setCameraPermission(cameraPermission.status === 'granted');

    const imagePermission = await ImagePicker.getMediaLibraryPermissionsAsync();
    console.log('permission:', imagePermission.status);

    setGalleryPermission(imagePermission.status === 'granted');

    if (
      imagePermission.status !== 'granted' &&
      cameraPermission.status !== 'granted'
    ) {
      alert('Permission for media access needed.');
    }
  };

  useEffect(() => {
    permisionFunction();
  }, []);

  const takePicture = async () => {
    if (camera) {
      const data = await camera.takePictureAsync(null);
      console.log(data.uri);
      setImageUri(data.uri);
      setImageArray([...imageArray, data.uri]);
      setShowCamera(false);
    }
  };

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      quality: 1,
    });

    console.log(result.uri);
    if (!result.cancelled) {
      setImageArray([...imageArray, result.uri]);
    }
  };

  return (
    <View style={styles.container}>
      {showCamera && (
        <Camera ref={(ref) => setCamera(ref)} style={{ flex: 1 }} type={type} />
      )}
      {showCamera && <Button title={'Click'} onPress={takePicture} />}
      {!showCamera && (
        <>
          <View
            style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
            <TextInput placeholder={'Enter PAN Number'} />
            <View style={{ flexDirection: 'row' }}>
              <Button
                title={'Camera'}
                onPress={() => {
                  setShowCamera(true);
                }}
              />
              <Button title={'Gallery'} onPress={pickImage} />
            </View>
          </View>
          {imageArray.length > 0 && (
            <View style={{ height: 110 }}>
              <FlatList
                horizontal
                data={imageArray}
                renderItem={({ item }) => (
                  <Image
                    source={{ uri: item }}
                    style={{
                      width: 100,
                      height: 100,
                      borderRadius: 10,
                      margin: 5,
                    }}
                  />
                )}
              />
            </View>
          )}
        </>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    marginTop: 30,
    flex: 1,
  },

  fixedRatio: {
    flex: 1,
  },
});


推荐阅读