美文网首页
react native图片宽度一定,高度自适应

react native图片宽度一定,高度自适应

作者: MasterPaul | 来源:发表于2020-01-08 15:10 被阅读0次

代码如下

import React from 'react';
import {
    Image,
    StyleSheet,
} from 'react-native';

import PropTypes from 'prop-types'

//图片自适应高度
export default class ImageAutoHeight extends React.PureComponent{

    constructor(props){
        super(props)


    }

    static propTypes = {

        source:PropTypes.any,
        width:PropTypes.number,
        style:PropTypes.object,
        setHeight:PropTypes.func
    }

    state = {
        imageH:100,

    };


    componentDidMount(){



        if(this.props.source.uri){
            console.log('网络图片')
            Image.getSize(this.props.source,(width, height)=>{

                this.setState({
                    imageH:this.props.width * height / width
                })
            })
        }else{
            console.log('本地资源')
            const result =  Image.resolveAssetSource(this.props.source)
            let height = result.height
            let width = result.width
            const finalHeight = this.props.width * height / width
            this.setState({
                imageH:finalHeight
            })
            this.props.setHeight && this.props.setHeight(finalHeight)
        }

    }

    render(){

        return (
            <Image
                style={[this.props.style,{height:this.state.imageH,width:this.props.width}]}
                source={this.props.source}
            />
        );
    }
}

调用如果是本地资源source={require('../../')},如果是网络资源source={{uri : ....}}
如果需要获取图片高度

    <ImageAutoHeight
                                source={{uri:this.state.url}}
                                width={screen.width}
                                 setHeight={height=>{    }}
                            />

相关文章

网友评论

      本文标题:react native图片宽度一定,高度自适应

      本文链接:https://www.haomeiwen.com/subject/ktrsactx.html