react:处理图片类似小程序mode: aspectFill

调整图片组件封装:

import './index.scss'

const ZoomImage = (props) => {
    
    const imageStyle = {
        backgroundImage: `url(${props.url})`
    }
    return (
        <>
            <div className="zoom-image" style={imageStyle}></div>
        </>
    )
}

export default ZoomImage

样式文件:

.zoom-image {
    width: 100%;
    height: 0;
    padding-bottom: 100%;

    overflow: hidden;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
}

虽然height:0;高度为0,但是它的padding值为100%
这是因为在padding为百分比的时候,是根据他父层的宽度来进行计算的。

padding-bottom: 100%; height = 1:1
padding-bottom: 75%; height = 4:3

使用:

<div className="item-image">
    <ZoomImage url="https://static.fczx.com/a/202102/05/8/8/b05d555922fcc6fd6cfa322270bbef49.png" />
</div>
.item-image {
                width: 215px;
                height: 172px;
                border-radius: $border-radius-base;
                background-color: $bg-color;
                overflow: hidden;     
}

原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/14378287.html