【问题标题】:Handle image loading in React在 React 中处理图像加载
【发布时间】:2017-12-20 17:34:19
【问题描述】:

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

{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>

这是标签的css代码

.price {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 0.95em;
    }

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

有没有好的解决方案?

谢谢!

PS:加载过程中是这样的

【问题讨论】:

    标签: javascript css image reactjs


    【解决方案1】:

    一个简单的解决方案是利用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} />
            )
        }
    }
    

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

    function VisImgExample({src}) {
      const [didLoad, setLoad] = React.useState(false);
    
      const style = didLoad ? {} : {visibility: 'hidden'};
    
      return <img style={style} src={src} onLoad={() => setLoad(true)} />;
    }
    

    【讨论】:

    • 您好,非常感谢。我希望有一种方法可以使用 alt 属性。但是这个解决方案效果很好。在我的示例中,我必须添加 {this.state.didLoad && },因为标签造成了麻烦。操作样式效果不佳,因为我使用 react-bootrstrap,它会覆盖图像组件的完整样式。
    • 糟糕,没有注意到这是针对 React 而不是 React Native。无论如何,谢谢你的钩子回答。对于 React Native,我必须将 visibility: 'hidden' 更改为 opacity: 0。我还必须在&lt;Image&gt; 中添加一个key={didLoad} 道具。
    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2019-03-30
    • 2011-07-01
    相关资源
    最近更新 更多