如何显示使用react native图像选择器选择的图像?

时间:2020-07-27 16:18:51

标签: react-native

问题:

我创建了带有react-native-image-picker的图像和视频选择器。这就是我的代码的样子。

import React, {useState, createRef} from 'react';
import {
  View,
  TouchableOpacity,
  Image,
  TouchableWithoutFeedback,
} from 'react-native';
import AppText from '_components/appText';
import Icon from 'react-native-vector-icons/AntDesign';
import {strings} from '_translations/i18n';
import styles from './newpatientassetmentstyle';
import PlayerControls from '_components/playerControls';
import Video from 'react-native-video';
import ImagePicker from 'react-native-image-picker';

const showControls = (state, setState) => {
  state.showControls
    ? setState({...state, showControls: false})
    : setState({...state, showControls: true});
};

const handlePlayPause = (state, setState) => {
  if (state.play) {
    setState({...state, play: false, showControls: true});
    return;
  }

  setState({...state, play: true});
  setTimeout(() => setState((s) => ({...s, showControls: false})), 2000);
};

function onLoadEnd(data, state, setState) {
  setState({
    ...state,
    duration: data.duration,
    currentTime: data.currentTime,
  });
}

function onProgress(data, state, setState) {
  setState({
    ...state,
    currentTime: data.currentTime,
  });
}

const onEnd = (state, setState, player) => {
  setState({
    ...state,
    showControls: false,
    play: false,
    currentTime: 0,
    duration: 0,
  });
  player.current.seek(0);
};

const openPicker = async (type, setFileObject) => {
  let options;
  if (type === 4) {
    options = {
      title: 'Upload Image',
      quality: 1,
      mediaType: 'photo',
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };
  } else if (type === 5) {
    options = {
      title: 'Upload Video',
      videoQuality: 'high',
      mediaType: 'video',
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };
  }

  ImagePicker.showImagePicker(options, (response) => {
    if (response.didCancel) {
      console.log('User cancelled image picker');
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    } else {
      setFileObject(response);
    }
  });
};

const DocumentUpload = (props) => {
  const {type} = props;
  const [fileObject, setFileObject] = useState(null);
  const [state, setState] = useState({
    fullscreen: false,
    play: false,
    currentTime: 0,
    duration: 0,
    showControls: true,
  });

  const player = createRef();
  return (
    <View>
      {type === 5 && (
        <View style={styles.videoContainer}>
          <View style={styles.videoInnerContainer}>
            <TouchableWithoutFeedback
              onPress={() => showControls(state, setState)}>
              <View style={{flex: 1}}>
                <Video
                  source={{
                    uri: fileObject.uri,
                  }}
                  controls={false}
                  style={styles.backgroundVideo}
                  ref={player}
                  resizeMode={'contain'}
                  paused={!state.play}
                  onEnd={() => onEnd(state, setState, player)}
                  onLoad={(data) => onLoadEnd(data, state, setState)}
                  onProgress={(data) => onProgress(data, state, setState)}
                />
                {state.showControls && (
                  <View style={styles.controlsOverlay}>
                    <PlayerControls
                      play={state.play}
                      playVideo={handlePlayPause}
                      state={state}
                      setState={setState}
                      pauseVideo={handlePlayPause}
                    />
                  </View>
                )}
              </View>
            </TouchableWithoutFeedback>
          </View>
        </View>
      )}
      {fileObject
        ? console.log(`data:${fileObject.type},${fileObject.data}`, 'fileOb')
        : null}
      {type === 4 && fileObject && (
        <View>
          <Image
            source={{uri: 'data:' + fileObject.type + ',' + fileObject.data}}
          />
        </View>
      )}
      {!fileObject ? (
        <>
          <TouchableOpacity onPress={() => openPicker(type, setFileObject)}>
            <Image
              source={require('_assets/img/cmerap.png')}
              resizeMode="center"
              style={styles.camPImage}
            />
          </TouchableOpacity>
          <AppText styles={styles.camPText}>
            {strings('assetsment.capture')}
          </AppText>
        </>
      ) : (
        <View style={styles.videoBottomText}>
          <TouchableOpacity onPress={() => openPicker(type, setFileObject)}>
            <View style={styles.updateAgainContainer}>
              <Icon name="reload1" style={styles.reloadIcon} />
              <AppText styles={styles.reloadText}>
                {strings('assetsment.reload')}
              </AppText>
            </View>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

export default DocumentUpload;

但是,当我尝试在视图中显示拾取的图像时,那里什么也没显示。我做了很多尝试,以找出问题所在,但未能做到。有人可以帮我找出解决这个问题的方法吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

一旦选择了图像,您将拥有一个响应对象,其中将具有所选图像的uri(您可以console.log响应对象以确保uri的键是什么)。将对象与响应一起使用后,请使用其uri设置状态,并确保在图像标签中使用该状态,如下所示:source={{ uri: imageUriFromState }}