반응에서 이미지 선택을 구현하는 방법
반응에서 이미지 선택을 구현하는 방법: 1. 가져오기를 사용하여 "react-native-image-picker" 플러그인을 도입합니다. 2. "
{this.setState({uploadImgs: urls})}}src=를 사용합니다. {uploadImgs}/> ;" 이미지를 선택하고 업로드하려면 호출하세요. ={6}onchange={urls>
이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 18.0.0, Dell G3 컴퓨터.
반응에서 이미지 선택을 구현하는 방법은 무엇입니까?
React 네이티브 Qiniu 업로드 + 로컬 이미지 선택
참고:
react-native-image-crop-picker图片选择并裁减 //这个看需求使用 https://github.com/ivpusic/react-native-image-crop-picker react-native-image-picker图片选择 https://github.com/react-native-image-picker/react-native-image-picker react-native-qiniu https://github.com/buhe/react-native-qiniu
다중 이미지 업로드 기능만 원해서 간단히 작성하겠습니다
Effect
업로드 상태
업로드 중 상태
단계
1. 휴대폰 사진 및 동영상 선택 기능
react-native-image-picker 플러그인을 사용하세요
yarn add-native-image-picker가 필요합니다.
import {launchCamera, launchImageLibrary, ImageLibraryOptions, PhotoQuality} from 'react-native-image-picker'; /** * 从相册选择图片; * sourceType: 'camera' 打开相机拍摄图片 **/ export async function chooseImage(options: { count?: number, quality?: PhotoQuality sourceType?: 'camera', //默认'album' } = {}) { return new Promise<any>(async(resolve, reject) => { const Opts: ImageLibraryOptions = { mediaType: 'photo', quality: options.quality || 1, selectionLimit: options.count || 1 }; const result = options.sourceType == 'camera'? await launchCamera(Opts) : await launchImageLibrary(Opts); resolve(result) }) } /** * 从相册选择视频; * sourceType: 'camera' 打开相机拍摄视频 **/ export async function chooseVideo(options: { count?: number, quality?: 'low' | 'high' sourceType?: 'camera', //默认'album' } = {}) { return new Promise<any>(async(resolve, reject) => { const Opts: ImageLibraryOptions = { mediaType: 'video', videoQuality: options.quality, selectionLimit: options.count || 1 }; const result = options.sourceType == 'camera'? await launchCamera(Opts) : await launchImageLibrary(Opts); resolve(result) }) }
2. 세븐카우 파일 업로드 기능
class qiniuUpload { private UP_HOST = 'http://upload.qiniu.com'; // private RS_HOST = 'http://rs.qbox.me'; // private RSF_HOST = 'http://rsf.qbox.me'; // private API_HOST = 'http://api.qiniu.com'; public upload = async(uri:string, key:string, token:string) => { return new Promise<any>((resolve, reject) => { let formData = new FormData(); formData.append('file', {uri: uri, type: 'application/octet-stream', name: key}); formData.append('key', key); formData.append('token', token); let options:any = { body: formData, method: 'post', }; fetch(this.UP_HOST, options).then((response) => { resolve(response) }).catch(error => { console.error(error) resolve(null) }); }) } //...后面再加别的功能 } const qiniu = new qiniuUpload(); export default qiniu; import qiniu from '@/modules/qiniu/index' ... /** * 上传视频图片 */ uploadFile: async (filePath: string) => { const res = await createBaseClient('GET', '/v1/file')(); //这是接口请求方法,用来拿后端的七牛token、key if( !res ) { return res; } const { key, token } = res; const fileSegments = filePath.split('.'); const fileKey = key + '.' + fileSegments[fileSegments.length - 1]; try { const result = await qiniu.upload(filePath, fileKey, token) if(result && result.ok) { return { url: ASSET_HOST + '/' + fileKey, //ASSET_HOST是资源服务器域名前缀 }; }else { return null } } catch (error) { return null; } }, ...
3. 다중 이미지 업로드 컴포넌트 캡슐화
(베이스, 이미지, 액션시트 모두 여기에 캡슐화되어 있어 상황에 따라 조정 필요)
import React from 'react' import { ViewStyle, StyleProp, ImageURISource, ActivityIndicator } from 'react-native' import Base from '@/components/Base'; import { Image, View, Text } from '@/components'; //Image封装过的,所以有些属性不一样 import ActionSheet from "@/components/Feedback/ActionSheet"; //自己封装 import styles from './styleCss'; //样式就不放上来了 interface Props { type?: 'video' src?: string[] count?: number btnPath?: ImageURISource style?: StyleProp<ViewStyle> itemStyle?: StyleProp<ViewStyle> itemWidth?: number itemHeight?: number //默认正方形 onChange?: (e) => void } interface State { imageUploading: boolean images: string[] } /** * 多图上传组件 * * type?: 'video' * * src?: string[] //图片数据,可用于初始数据 * * count?: number //数量 * * btnPath?: ImageURISource //占位图 * * itemStyle?: item样式,width, height单独设 * * itemWidth?: number * * itemHeight?: number //默认正方形 * * onChange?: (e:string[]) => void **/ export default class Uploader extends Base<Props, State> { public state: State = { imageUploading: false, images: [] }; public didMount() { this.initSrc(this.props.src) } public componentWillReceiveProps(nextProps){ if(nextProps.hasOwnProperty('src') && !!nextProps.src){ this.initSrc(nextProps.src) } } /** *初始化以及改动图片 **/ private initSrc = (srcProp:any) => { if(!this.isEqual(srcProp, this.state.images)) { this.setState({ images: srcProp }) } } public render() { const { style, btnPath, count, itemStyle, itemWidth, itemHeight, type } = this.props; const { imageUploading, images } = this.state; let countNumber = count? count: 1 return ( <React.Fragment> <View style={[styles.uploaderBox, style]}> {images.length > 0 && images.map((res, ind) => ( <View style={[styles.item, itemStyle]} key={res}> <View style={styles.imgItem}> <Image source={{uri: res}} width={this.itemW} height={this.itemH} onPress={() => { this.singleEditInd = ind; this.handleShowActionSheet() }} /> <Text style={styles.del} onPress={this.handleDelete.bind(null, ind)}>删除</Text> </View> </View> ))} {images.length < countNumber && <View style={[styles.item, itemStyle]}> {imageUploading? ( <View style={[{ width: this.itemW, height: this.itemH, }, styles.loading]}> <ActivityIndicator size={this.itemW*0.4}></Loading> <Text style={{ fontSize: 14, color: '#888', marginTop: 5 }}> 上传中... </Text> </View> ): ( <View style={styles.btn}> <Image source={btnPath || this.assets.uploadIcon} width={this.itemW} height={this.itemH} onPress={() => { this.singleEditInd = undefined; this.handleShowActionSheet() }} /> </View> )} </View> } </View> <ActionSheet name="uploaderActionSheet" options={[{ name: type == 'video'? '拍摄': '拍照', onClick: () => { if(type == 'video') { this.handleChooseVideo('camera') }else if(this.singleEditInd !== undefined) { this.handleChooseSingle('camera') }else { this.handleChooseImage('camera') } } }, { name: '相册', onClick: () => { if(type == 'video') { this.handleChooseVideo() }else if(this.singleEditInd !== undefined) { this.handleChooseSingle() }else { this.handleChooseImage() } } }]} ></ActionSheet> </React.Fragment> ); } private get itemW() { return this.props.itemWidth || 92 } private get itemH() { return this.props.itemHeight || this.itemW; } private isEqual = (firstValue, secondValue) => { /** 判断两个值(数组)是否相等 **/ if (Array.isArray(firstValue)) { if (!Array.isArray(secondValue)) { return false; } if(firstValue.length != secondValue.length) { return false; } return firstValue.every((item, index) => { return item === secondValue[index]; }); } return firstValue === secondValue; } private handleShowActionSheet = () => { this.feedback.showFeedback('uploaderActionSheet'); //这是显示ActionSheet选择弹窗。。。 } private handleChooseImage = async (sourceType?: 'camera') => { const { imageUploading, images } = this.state; const { count } = this.props if (imageUploading) { return; } let countNumber = count? count: 1 const { assets } = await this.interface.chooseImage({ //上面封装的选择图片方法 count: countNumber, sourceType: sourceType || undefined, }); if(!assets) { return; } this.setState({ imageUploading: true, }); let request:any = [] assets.map(res => { let req = this.apiClient.uploadFile(res.uri) //上面封装的七牛上传方法 request.push(req) }) Promise.all(request).then(res => { let imgs:any = [] res.map((e:any) => { if(e && e.url){ imgs.push(e.url) } }) imgs = [...images, ...imgs]; this.setState({ images: imgs.splice(0,countNumber), imageUploading: false, }, this.handleChange ); }) } private singleEditInd?: number; //修改单个时的索引值 private handleChooseSingle = async(sourceType?: 'camera') => { let { imageUploading, images } = this.state; if (imageUploading) { return; } const { assets } = await this.interface.chooseImage({ //上面封装的选择图片方法 count: 1, sourceType: sourceType || undefined, }); if(!assets) { return; } this.setState({ imageUploading: true, }); const res = await this.apiClient.uploadFile(assets[0].uri) //上面封装的七牛上传方法 if(res && res.url && this.singleEditInd){ images[this.singleEditInd] = res.url } this.setState({ images: [...images], imageUploading: false, }, this.handleChange ); } private handleChooseVideo = async(sourceType?: 'camera') => { const { onChange } = this.props let { imageUploading } = this.state; if (imageUploading) { return; } const { assets } = await this.interface.chooseVideo({ sourceType: sourceType }); if(!assets) { return; } this.setState({ imageUploading: true, }); const res = await this.apiClient.uploadFile(assets[0].uri) //上面封装的七牛上传方法 if(res && res.url){ //视频就不在组件中展示了,父组件处理 if(onChange) { onChange(res.url) } } this.setState({ imageUploading: false, }); } private handleDelete = (ind:number) => { let { images } = this.state images.splice(ind,1) this.setState({ images: [...images] }, this.handleChange ) } private handleChange = () => { const { onChange } = this.props const { images } = this.state if(onChange) { onChange(images) } } }
4.
추천 학습: "react 비디오 튜토리얼》
위 내용은 반응에서 이미지 선택을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











React와 WebSocket을 사용하여 실시간 채팅 애플리케이션을 구축하는 방법 소개: 인터넷의 급속한 발전과 함께 실시간 커뮤니케이션이 점점 더 주목을 받고 있습니다. 실시간 채팅 앱은 현대 사회 생활과 직장 생활에서 필수적인 부분이 되었습니다. 이 글에서는 React와 WebSocket을 사용하여 간단한 실시간 채팅 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 기술적 준비 실시간 채팅 애플리케이션 구축을 시작하기 전에 다음과 같은 기술과 도구를 준비해야 합니다. React: 구축을 위한 것

React 프론트엔드와 백엔드 분리 가이드: 프론트엔드와 백엔드 분리 및 독립적 배포를 달성하는 방법, 구체적인 코드 예제가 필요합니다. 오늘날의 웹 개발 환경에서는 프론트엔드와 백엔드 분리가 추세가 되었습니다. . 프런트엔드 코드와 백엔드 코드를 분리함으로써 개발 작업을 보다 유연하고 효율적으로 수행하고 팀 협업을 촉진할 수 있습니다. 이 기사에서는 React를 사용하여 프런트엔드와 백엔드 분리를 달성하고 이를 통해 디커플링 및 독립적 배포 목표를 달성하는 방법을 소개합니다. 먼저 프론트엔드와 백엔드 분리가 무엇인지 이해해야 합니다. 전통적인 웹 개발 모델에서는 프런트엔드와 백엔드가 결합되어 있습니다.

React와 Flask를 사용하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축하는 방법 소개: 인터넷의 발전과 함께 웹 애플리케이션의 요구 사항은 점점 더 다양해지고 복잡해지고 있습니다. 사용 편의성과 성능에 대한 사용자 요구 사항을 충족하기 위해 최신 기술 스택을 사용하여 네트워크 애플리케이션을 구축하는 것이 점점 더 중요해지고 있습니다. React와 Flask는 프런트엔드 및 백엔드 개발을 위한 매우 인기 있는 프레임워크이며, 함께 잘 작동하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축합니다. 이 글에서는 React와 Flask를 활용하는 방법을 자세히 설명합니다.

React 및 RabbitMQ를 사용하여 안정적인 메시징 애플리케이션을 구축하는 방법 소개: 최신 애플리케이션은 실시간 업데이트 및 데이터 동기화와 같은 기능을 달성하기 위해 안정적인 메시징을 지원해야 합니다. React는 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 반면 RabbitMQ는 안정적인 메시징 미들웨어입니다. 이 기사에서는 React와 RabbitMQ를 결합하여 안정적인 메시징 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. RabbitMQ 개요:

React 반응형 디자인 가이드: 적응형 프런트엔드 레이아웃 효과를 달성하는 방법 모바일 장치의 인기와 멀티스크린 경험에 대한 사용자 요구가 증가함에 따라 반응형 디자인은 현대 프런트엔드 개발에서 중요한 고려 사항 중 하나가 되었습니다. 현재 가장 인기 있는 프런트 엔드 프레임워크 중 하나인 React는 개발자가 적응형 레이아웃 효과를 달성하는 데 도움이 되는 풍부한 도구와 구성 요소를 제공합니다. 이 글에서는 React를 사용하여 반응형 디자인을 구현하는 데 대한 몇 가지 지침과 팁을 공유하고 참조할 수 있는 구체적인 코드 예제를 제공합니다. React를 사용한 Fle

React 코드 디버깅 가이드: 프런트엔드 버그를 빠르게 찾고 해결하는 방법 소개: React 애플리케이션을 개발할 때 애플리케이션을 충돌시키거나 잘못된 동작을 유발할 수 있는 다양한 버그에 자주 직면하게 됩니다. 따라서 디버깅 기술을 익히는 것은 모든 React 개발자에게 필수적인 능력입니다. 이 기사에서는 프런트엔드 버그를 찾고 해결하기 위한 몇 가지 실용적인 기술을 소개하고 독자가 React 애플리케이션에서 버그를 빠르게 찾고 해결하는 데 도움이 되는 특정 코드 예제를 제공합니다. 1. 디버깅 도구 선택: In Re

ReactRouter 사용자 가이드: 프런트엔드 라우팅 제어 구현 방법 단일 페이지 애플리케이션의 인기로 인해 프런트엔드 라우팅은 무시할 수 없는 중요한 부분이 되었습니다. React 생태계에서 가장 널리 사용되는 라우팅 라이브러리인 ReactRouter는 풍부한 기능과 사용하기 쉬운 API를 제공하여 프런트 엔드 라우팅 구현을 매우 간단하고 유연하게 만듭니다. 이 기사에서는 ReactRouter를 사용하는 방법을 소개하고 몇 가지 구체적인 코드 예제를 제공합니다. ReactRouter를 먼저 설치하려면 다음이 필요합니다.

React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법 소개: 오늘날 정보 폭발 시대에 데이터 분석은 다양한 산업에서 없어서는 안 될 연결 고리가 되었습니다. 그중에서도 빠르고 효율적인 데이터 분석 애플리케이션을 구축하는 것은 많은 기업과 개인이 추구하는 목표가 되었습니다. 이 기사에서는 React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법을 소개하고 자세한 코드 예제를 제공합니다. 1. 개요 React는 빌드를 위한 도구입니다.
