在 React 中处理图像加载

Mic*_*zum 4 javascript css image reactjs

我正在使用此代码加载图像

{Image} from 'react-bootstrap';
<Image src={res.imgUrl} className={styles.image} onError={(e)=>{e.target.src="/defaultImage.png"}} responsive thumbnail />
<Label bsStyle="primary" className={styles.price}}>{Price} &#8364;</Label>
Run Code Online (Sandbox Code Playgroud)

这是标签的css代码

.price {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 0.95em;
    }
Run Code Online (Sandbox Code Playgroud)

它工作正常。但是在加载过程中,“标签”元素显示的不是很好,因为还没有加载的图像并且没有足够的位置来显示。

对此有一个很好的解决方案吗?

谢谢!

PS:加载时是这样的

在此处输入图片说明

enj*_*ife 9

一个简单的解决方案是利用该onLoad事件和一个didLoad标志来延迟渲染图像,直到它完全加载。

class Example extends Component {

    constructor(props) {
        super(props);

        this.state = {
            didLoad: false
        }
    }

    onLoad = () => {
        this.setState({
            didLoad: true
        })
    }


    render() {
        const style = this.state.didLoad ? {} : {visibility: 'hidden'}
        return (
            <img style={style} src={this.props.src} onLoad={this.onLoad} />
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

根据要求,使用hooks的示例:

function VisImgExample({src}) {
  const [didLoad, setLoad] = React.useState(false);

  const style = didLoad ? {} : {visibility: 'hidden'};

  return <img style={style} src={src} onLoad={() => setLoad(true)} />;
}
Run Code Online (Sandbox Code Playgroud)