ReactNative: 使用Image圖片組件


一、簡介

在應用程序中,圖片組件非常常見,不論是縮略圖、大圖、還是小圖標等等,都需要使用圖片組件進行顯示。在Web開發中提供了<img/>標簽顯示圖片,在iOS中提供了UIImageView顯示圖片,而在RN中,則使用Image組件顯示圖片。同樣的道理,Image組件既可以顯示本地圖片(磁盤、相冊),也可以顯示網絡圖片。

 

二、詳情

1、屬性

//枚舉類型,表示圖片的適應模模式
//cover:覆蓋  contain:包含  stretch:平鋪
resizeMode

//圖片的引用地址,網絡資源值為{uri:string},靜態資源值為require('image!name')
source

//iOS支持的屬性,表示默認圖片,相當於占位圖,網絡圖片加載完成后被替換
defaultSource 

2、事件

//iOS支持的屬性,表示在圖片加載成功時觸發該函數
onLoad

//iOS支持的屬性,表示在圖片開始加載時觸發該函數
onLoadStart

//iOS支持的屬性,表示在圖片加載不管成功還是失敗都會觸發該函數
onLoadEnd

//iOS支持的屬性,顯示加載圖片的進度
onProgress 

3、加載

//網絡圖片
<Image source = {{uri: "https://www.xxx.png"}} />

//本地圖片
//1、加載項目文件夾中的圖片
<Image source=require('../xx/xx/iconName')>

//2、加載(APP)Xcode中的圖片
<Image source={{uri:'iconName'}}>


//-----------------------------------注意事項-------------------------------------------//

//1、一些老文章和教程提到的require('image!xxx')的寫法已經從0.40版本開始不再支持!,例如:
<Image source = require('image!iconName') />

//2、為了使新的圖片資源機制正常工作,require中的圖片名字必須是一個靜態字符創(不能使用變量!因為require是在編譯時期執行,而非運行時期執行!)如下所示:

//正確
<Image source = require('./iconName.png) />

//正確
var icon = showBigIcon ? require('./bigIconName.png') : require('smallIconName.png');
<Image source={icon} />

//錯誤
var icon = showBigIcon ?  'bigIconName' : 'smallIconName';
<Image source={require('./' + icon + '.png')} />
 

  

三、使用

1、網絡圖片【注意:需要在Xcode的plist中設置NSAppTransportSecuriyt的Allow Arbitrary Loads=YES】

ImageView.js

import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
} from 'react-native'

export default class ImageView extends  Component{

    //默認屬性放在state中
    constructor(){
        super();
        this.state = {
            index:0,
            images:[
                "http://img.souutu.com/2019/1031/20191031103506146.jpg.260.343.jpg",
                "http://img.mm8mm8.com/thumb/279x210/11/19/1119263f972f1d4cc2aff85fa199fe11.jpeg"
            ]
        }
    }

    //下一張
    next = () => {
        const {index,images} = this.state;
        const count = images.length-1;
        if (index+1 > count) {
            alert("圖片已經到最后一張");
            return;
        }
        const current = index+1;
        this.setState({index:current})
    };

    //上一張
    previous = () => {
        const {index} = this.state;
        if (index-1 < 0){
            alert("圖片已經到第一張");
         return; } const current = index-1;
        this.setState({index:current}) };

    render(){
        let {images,index} = this.state;
        return (
            <View style={styles.flex}>
                <View style={styles.container}>
                    <Image
                        style={styles.image}
                        source={{uri:images[index]}}
                    />
                </View>
                <View style={styles.flexDirection}>
                    <View style={[styles.previous,styles.center]}>
                        <TouchableOpacity onPress={this.previous.bind(this)}>
                            <View>
                                <Text style={styles.font}>上一張</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={[styles.next,styles.center]}>
                        <TouchableOpacity activeOpacity={0.2} onPress={this.next.bind(this)}>
                            <View>
                                <Text style={styles.font}>下一張</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    flex: {
        flex: 1
    },
    container: {
        marginTop: 30,
        height: 300,
        marginLeft: 10,
        marginRight: 10,
        borderColor: 'red',
        borderWidth: 1,
        borderRadius: 4,
        justifyContent: 'center',
        alignItems: 'center'
    },
    image: {
        width: 200,
        height: 250
    },
    flexDirection: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    next: {
        height: 45,
        width: 80,
        backgroundColor: 'green',
        marginLeft: 20,
        marginTop: 20,
        borderWidth: 1,
        borderRadius: 4,
        borderColor: 'green'
    },
    previous: {
        height: 45,
        width: 80,
        backgroundColor: 'green',
        marginRight: 20,
        marginTop: 20,
        borderWidth: 1,
        borderRadius: 4,
        borderColor: 'green'
    },
    center: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    font: {
        fontWeight: 'bold',
        fontSize: 20,
        textAlign: 'center',
        color: 'white'
    }
});

index.ios.js

/** * Sample React Native App * https://github.com/facebook/react-native * @flow */

import React, { Component } from 'react';
import ImageView from './src/ImageView'

import {
    AppRegistry,
} from 'react-native';

export default class ReactNativeDemo extends Component {

    render() {
        return (
            <ImageView/>
        );
    }
}

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

 

2、本地圖片

2-1 在項目中添加圖片並加載

ImageView.js

import React, { Component } from 'react';

import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
} from 'react-native'

export default class ImageView extends  Component{

    //默認屬性放在state中, 這里加載本地項目圖片
    constructor(){
        super();
        this.state = {
            index:0,
            images:[
                require('../image/flower1.png'),
                require('../image/flower2.png'),
                require('../image/flower3.png')
            ]
        }
    }

    //下一張
    next = () => {
        const {index,images} = this.state;
        const count = images.length-1;
        if (index+1 > count) {
            alert("圖片已經到最后一張");
            return;
        }
        const current = index+1;
        this.setState({index:current})
    };

    //上一張
    previous = () => {
        const {index} = this.state;
        if (index-1 < 0){
            alert("圖片已經到第一張");
         return; } const current = index-1;
        this.setState({index:current}) };

    render(){

        let {images,index} = this.state;

        return (
            <View style={styles.flex}>
                <View style={styles.container}>
                    <Image
                        style = {styles.image}
                        source = {images[index]}
                    />
                </View>
                <View style={styles.flexDirection}>
                    <View style={[styles.previous,styles.center]}>
                        <TouchableOpacity onPress={this.previous.bind(this)}>
                            <View>
                                <Text style={styles.font}>上一張</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={[styles.next,styles.center]}>
                        <TouchableOpacity activeOpacity={0.2} onPress={this.next.bind(this)}>
                            <View>
                                <Text style={styles.font}>下一張</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    flex: {
        flex: 1
    },
    container: {
        marginTop: 30,
        height: 300,
        marginLeft: 10,
        marginRight: 10,
        borderColor: 'red',
        borderWidth: 1,
        borderRadius: 4,
        justifyContent: 'center',
        alignItems: 'center'
    },
    image: {
        width: 200,
        height: 250
    },
    flexDirection: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    next: {
        height: 45,
        width: 80,
        backgroundColor: 'green',
        marginLeft: 20,
        marginTop: 20,
        borderWidth: 1,
        borderRadius: 4,
        borderColor: 'green'
    },
    previous: {
        height: 45,
        width: 80,
        backgroundColor: 'green',
        marginRight: 20,
        marginTop: 20,
        borderWidth: 1,
        borderRadius: 4,
        borderColor: 'green'
    },
    center: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    font: {
        fontWeight: 'bold',
        fontSize: 20,
        textAlign: 'center',
        color: 'white'
    }
}); 

index.ios.js

/** * Sample React Native App * https://github.com/facebook/react-native * @flow */

import React, { Component } from 'react';
import ImageView from './src/ImageView'

import {
    AppRegistry,
} from 'react-native';

export default class ReactNativeDemo extends Component {

    render() {
        return (
            <ImageView/>
        );
    }
}

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

 2-2 在Xcode中添加圖片並加載

ImageView.js

import React, { Component } from 'react';

import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
} from 'react-native'

export default class ImageView extends  Component{

    //默認屬性放在state中
    constructor(){
        super();
        this.state = {
            index:0,
            images:[
                'car1.png',
                'car2.png'
            ]
        }
    }

   //下一張
    next = () => {
        const {index,images} = this.state;
        const count = images.length-1;
        if (index+1 > count) {
            alert("圖片已經到最后一張");
            return;
        }
        const current = index+1;
        this.setState({index:current})
    };

   //上一張
    previous = () => {
        const {index} = this.state;
        if (index-1 < 0){
            alert("圖片已經到第一張");
       return; } const current = index-1;
        this.setState({index:current}) }; 
    render(){

        let {images,index} = this.state;

        return (
            <View style={styles.flex}>
                <View style={styles.container}>
                    <Image
                        style = {styles.image}
                        source = {{uri:`${images[index]}`}}
                    />
                </View>
                <View style={styles.flexDirection}>
                    <View style={[styles.previous,styles.center]}>
                        <TouchableOpacity onPress={this.previous.bind(this)}>
                            <View>
                                <Text style={styles.font}>上一張</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={[styles.next,styles.center]}>
                        <TouchableOpacity activeOpacity={0.2} onPress={this.next.bind(this)}>
                            <View>
                                <Text style={styles.font}>下一張</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    flex: {
        flex: 1
    },
    container: {
        marginTop: 30,
        height: 300,
        marginLeft: 10,
        marginRight: 10,
        borderColor: 'red',
        borderWidth: 1,
        borderRadius: 4,
        justifyContent: 'center',
        alignItems: 'center'
    },
    image: {
        width: 200,
        height: 250
    },
    flexDirection: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    next: {
        height: 45,
        width: 80,
        backgroundColor: 'green',
        marginLeft: 20,
        marginTop: 20,
        borderWidth: 1,
        borderRadius: 4,
        borderColor: 'green'
    },
    previous: {
        height: 45,
        width: 80,
        backgroundColor: 'green',
        marginRight: 20,
        marginTop: 20,
        borderWidth: 1,
        borderRadius: 4,
        borderColor: 'green'
    },
    center: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    font: {
        fontWeight: 'bold',
        fontSize: 20,
        textAlign: 'center',
        color: 'white'
    }
});

index.ios.js

/** * Sample React Native App * https://github.com/facebook/react-native * @flow */

import React, { Component } from 'react';
import ImageView from './src/ImageView'

import {
    AppRegistry,
} from 'react-native';

export default class ReactNativeDemo extends Component {

    render() {
        return (
            <ImageView/>
        );
    }
}

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

  

四、打包

ReactNative打包bundle后使用Xcode內的圖片,可以參考其他博主鏈接試試:https://www.jianshu.com/p/516db3de199b

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM