React Native with Typescript

[ReactNative-3] Image Picker 사용해서 원하는 프레임에 사진 업로드

아직개구리 2023. 2. 12. 23:54

참고한 자료는 https://github.com/dev-yakuza/react-native-image-picker-example/blob/master/src/App.tsx

 

GitHub - dev-yakuza/react-native-image-picker-example

Contribute to dev-yakuza/react-native-image-picker-example development by creating an account on GitHub.

github.com

이전 버전으로 작성되어있던 터라 버전을 업데이트 하면서 몇가지를 수정해줘야 했다. 

  1. 먼저 styled-components를 다운로드 받아서 사용하는데, react18과 버전 충돌이 있어서 styled-components를 --force flag를 사용해서 다운로드 해주었다. 
  2. react-native-image-picker: npm install react-native-image-picker 후에 cd ios && pod install을 해줘야한다. 
  3. react-native-image-picker 변경사항: import 하는 방식이 달라졌다. (아래 코드 첨부), 그리고 showImagePicker 가 없어서 camera를 사용할것인지, 갤러리를 통해 불러올 것인지를 보여주는 방식은 따로 추가해야한다. 
  4.  https://github.com/styled-components/styled-components/issues/2099 : 이 이슈로 styled components쓰는것에 에러가 났었는데, tsconfig.json의 compilerOptions에 types: ["styled-components-react-native"]를 추가해주고 해결되었다. 

 

import React, {useState} from 'react';
import styled from 'styled-components/native';
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';

const App = () => {
  const [imageSource, setImageSource] = useState<string | undefined>(undefined);

  const showCamera = (): void => {
    launchCamera({mediaType: 'photo', durationLimit: 10}, response => {
      console.log(response);
      if (response.errorCode) {
        console.log('LaunchCamera Error: ', response.errorCode);
      } else {
        setImageSource(response.assets[0].uri);
      }
    });
  };

  const showCameraRoll = (): void => {
    launchImageLibrary({selectionLimit: 1, mediaType: 'photo'}, response => {
      if (response.errorCode) {
        console.log('LaunchImageLibrary Error: ', response.errorCode);
      } else {
        setImageSource(response.assets[0].uri);
      }
    });
  };

  return (
    <Container>
      {imageSource && <Photo source={{uri: imageSource}} />}
      <ImagePickerButton onPress={showCamera}>
        <Label>Take Photo</Label>
      </ImagePickerButton>
      <ImagePickerButton onPress={showCameraRoll}>
        <Label>Show Camera Roll</Label>
      </ImagePickerButton>
    </Container>
  );
};

export default App;

 

 

 

 

 

'React Native with Typescript' 카테고리의 다른 글

[ReactNative-2] Component Style  (0) 2023.02.05
[ReactNative-1] Mobile App 개발 시작  (0) 2023.01.29