繁体   English   中英

react-native 使用钩子从图库中加载图像列表,

[英]react-native loading a list of images from gallery using hooks,

我使用 react native 和 hooks 来制作一个视图,我可以选择用我的相机拍照或打开我的手机图库并选择我想要的任何图像,一旦我有一张照片,它应该在列表中显示图像,所以如果我选择多张图片它应该在列表中显示多张图片。

const Seleccion = ({navigation}) => {
  const [fileList, setFileList] = useState([]);
  const state = useMemo(() => ({ fileList }), [fileList]);

  const onSelectedImage = useCallback((image) => {
    setFileList(fileList => {
      const newDataImg = [...fileList];
      const source = { uri: image.path };
      const item = {
        id: Date.now(),
        url: source,
        content: image.data
      };
      newDataImg.push(item);
      return newDataImg;
    });
  }, [setFileList]);

  const takePhotoFromCamera = useCallback(() => {
    ImagePicker.openCamera({
      width: 300,
      height: 400,
    }).then(image => {
      onSelectedImage(image);
      console.log(image);
    });
  }, [onSelectedImage]);

  const choosePhotoFromLibrary = useCallback(() => {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
    }).then(image => {
      onSelectedImage(image);
      console.log(image);
    });
  }, [onSelectedImage]);

  const renderItem = useCallback(({ item, index }) => {
    return (
      <View>
        <Image source={item.url} style={styles.itemImage} />
      </View>
    );
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        data={fileList}
        keyExtractor={(item, index) => index.toString()}
        renderItem={renderItem}
        extraData={state}
      />

      <TouchableOpacity style={styles.viewData} onPress={takePhotoFromCamera}>
        <Text>Foto</Text>
      </TouchableOpacity>

      <TouchableOpacity style={styles.viewData} onPress={choosePhotoFromLibrary}>
        <Text>galeria</Text>
      </TouchableOpacity>
    </View>
  );
}

这是我在样本中的脏组件,看看它:

import React, {useState, useEffect, Fragment} from 'react';
import Icon from 'react-native-vector-icons/FontAwesome5Pro';
import {
  View,
  Modal,
  ScrollView,
  Image,
  TouchableOpacity,
  Text,
} from 'react-native';
import ActionSheet from 'react-native-action-sheet';
import ImagePicker from 'react-native-image-crop-picker';
import ImageViewer from 'react-native-image-zoom-viewer';

import styles from '../../../../../../styles';

const BUTTONS = ['Gallery', 'Camera', 'Cancel'];

export default props => {
  let {files, setFiles} = props;
  const [ImageViwerIsVisible, showImageViwer] = useState(false);
  let [viewingIndex, setViewingIndex] = useState(-1);

  useEffect(() => {
    viewingIndex !== -1 && showImageViwer(true);
  }, [viewingIndex]);

  useEffect(() => {
    !ImageViwerIsVisible && setViewingIndex(-1);
  }, [ImageViwerIsVisible]);

  const showActionSheet = () =>
    ActionSheet.showActionSheetWithOptions(
      {
        title: 'Choose photo location',
        options: BUTTONS,
        cancelButtonIndex: 2,
        destructiveButtonIndex: 2,
        tintColor: 'blue',
      },
      buttonIndex => {
        switch (buttonIndex) {
          case 0:
            return selectFromGallery();
          case 1:
            return selectFromCamera();
          default:
            return 0;
        }
      },
    );

  const selectFromGallery = () =>
    ImagePicker.openPicker({
      multiple: true,
      //cropping: true,
    })
      .then(image => {
        setFiles([...files, image].flat());
      })
      .catch(e => {});
  const selectFromCamera = () =>
    ImagePicker.openCamera({
      cropping: true,
      includeExif: true,
    })
      .then(image => {
        setFiles([...files, image]);
      })
      .catch(e => {});
  return (
    <Fragment>
      {!!ImageViwerIsVisible && (
        <Modal transparent={true} onRequestClose={() => showImageViwer(false)}>
          <ImageViewer
            imageUrls={files.map(f => ({url: f.path}))}
            index={viewingIndex}
          />
        </Modal>
      )}
      <View
        style={{
          flexDirection: 'row',
          padding: 10,
          backgroundColor: '#ececec',
          marginBottom: 5,
        }}>
        <TouchableOpacity onPress={() => showActionSheet()}>
          <Icon solid name="camera-retro" size={32} />
        </TouchableOpacity>
        {/* <Text>{JSON.stringify(files, null, 2)}</Text> */}
        <ScrollView style={{flexDirection: 'row', flex: 1}} horizontal>
          {files.map((file, index) => (
            <TouchableOpacity
              key={file.path}
              onPress={() => setViewingIndex(index)}
              onLongPress={() =>
                ImagePicker.cleanSingle(file.path)
                  .then(() => setFiles(files.filter(f => f.path !== file.path)))
                  .catch(e => {})
              }
              style={{
                marginRight: 5,
                width: 50,
                height: 50,
                borderWidth: 1,
                borderColor: '#000',
                borderRadius: 5,
              }}>
              <Image
                source={{uri: file.path}}
                style={{width: '100%', height: '100%', borderRadius: 5}}
              />
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>
    </Fragment>
  );
};

您需要在代码中使用useCallBack ,那时我对react-hooks

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM