使用样式组件实现图像的延迟加载

我们正在使用样式组件在屏幕上渲染图像。我想要实现的是图像应该以惰性方式加载,我们首先加载分辨率较低的图像,然后加载高分辨率的图像。这就是我想要做的。


const Imagephone = styled.div`

  // width: 25.5rem;

  // width: 21rem;

  width: 23.75rem;

  height: 48.230rem;

  margin: 0 auto;

  background: ${props => props.primary ? "palevioletred" : "white"};

  background-image: url(${props => !props.loaded || props.error ?

  `https://some url`:

    `https://some url2`

  }) ;



  background-repeat: no-repeat;

  background-size: cover;

  position: relative;

  top: ;`



在我的课上我有这个


    super(props);

    this.state = {

      loaded: false,

      error: false

    };

  }


  componentDidMount() {

    const img = new Image();

    debugger

    img.onload = () => {

      debugger

      this.setState({

        loaded: true

      });

      debugger

    };

    img.onerror = () => {

      this.setState({

        error: true

      });

    };


  }```

and in my render i am doing this .

     <Imagephone loaded={this.state.loaded} error={this.state.error} />

` 我担心的是,在组件安装和图像加载后,我们需要将加载状态设置为真,但这部分不会被执行。我没有看到 img.onload 被执行。我们如何在延迟加载图像的情况下实现它。


暮色呼如
浏览 198回答 2
2回答

qq_遁去的一_1

问题是您正在创建一个新Image实例并依赖于它的onload和onerror方法。但是,您需要使用渲染img的元素onLoad和onError道具。const LazyImage = ({ loadingSrc, actualSrc, errorSrc, ...props }) => {&nbsp; const [isImageLoaded, setImageLoaded] = React.useState(false);&nbsp; const [hasError, setHasError] = React.useState(false);&nbsp;&nbsp;&nbsp; const src = React.useMemo(() => {&nbsp; &nbsp; if (hasError) {&nbsp; &nbsp; &nbsp; return errorSrc;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (isImageLoaded) {&nbsp; &nbsp; &nbsp; return actualSrc;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return loadingSrc;&nbsp; }, [hasError, isImageLoaded])&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <img&nbsp; &nbsp; &nbsp; src={src}&nbsp; &nbsp; &nbsp; onLoad={() => setImageLoaded(true)}&nbsp; &nbsp; &nbsp; onError={() => setHasError(true)}&nbsp; &nbsp; &nbsp; {...props}&nbsp; &nbsp; />&nbsp; )}const App = () => (&nbsp; <LazyImage&nbsp; &nbsp; loadingSrc="https://media3.giphy.com/media/17mNCcKU1mJlrbXodo/giphy.gif"&nbsp; &nbsp; actualSrc="https://hackernoon.com/hn-images/1*y6C4nSvy2Woe0m7bWEn4BA.png"&nbsp; &nbsp; errorSrc="https://kuwaitlifestyleblog.files.wordpress.com/2016/07/windows_bug6-100581894-primary-idge.jpg?w=608&h=405"&nbsp; &nbsp; width={300}&nbsp; &nbsp; style={{ margin: '0 auto', display: 'block' }}&nbsp; />)ReactDOM.render(<App />, document.getElementById('root'))<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script><div id="root"></div>编辑:使用styled-components:const StyledImage = styled.div`&nbsp; background-image: url("${props => props.error ? props.errorSrc : (props.loading ? props.loadingSrc : props.actualSrc)}");&nbsp; background-position: center center;&nbsp; background-size: contain;&nbsp; width: 300px;&nbsp; height: 200px;&nbsp; display: block;&nbsp; margin: 0 auto;`;const LazyImage = ({ loadingSrc, actualSrc, errorSrc, ...props }) => {&nbsp; const [isImageLoaded, setImageLoaded] = React.useState(false);&nbsp; const [hasError, setHasError] = React.useState(false);&nbsp;&nbsp;&nbsp; React.useEffect(() => {&nbsp; &nbsp; const img = new Image();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; img.onload = () => setImageLoaded(true);&nbsp; &nbsp; img.onerror = () => setHasError(true);&nbsp; &nbsp; img.src = actualSrc;&nbsp; }, [actualSrc])&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <StyledImage&nbsp; &nbsp; &nbsp; loadingSrc={loadingSrc}&nbsp; &nbsp; &nbsp; actualSrc={actualSrc}&nbsp; &nbsp; &nbsp; errorSrc={actualSrc}&nbsp; &nbsp; &nbsp; loading={!isImageLoaded}&nbsp; &nbsp; &nbsp; error={hasError}&nbsp; &nbsp; &nbsp; {...props}&nbsp; &nbsp; />&nbsp; )}const App = () => (&nbsp; <LazyImage&nbsp; &nbsp; loadingSrc="https://media3.giphy.com/media/17mNCcKU1mJlrbXodo/giphy.gif"&nbsp; &nbsp; actualSrc="https://hackernoon.com/hn-images/1*y6C4nSvy2Woe0m7bWEn4BA.png"&nbsp; &nbsp; errorSrc="https://kuwaitlifestyleblog.files.wordpress.com/2016/07/windows_bug6-100581894-primary-idge.jpg?w=608&h=405"&nbsp; />)ReactDOM.render(<App />, document.getElementById('root'))<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script><div id="root"></div>

慕侠2389804

你的图像需要一个 src 来加载一些东西:&nbsp; componentDidMount() {&nbsp; &nbsp; const img = new Image();&nbsp; &nbsp; debugger&nbsp; &nbsp; img.onload = () => {&nbsp; &nbsp; &nbsp; debugger&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; loaded: true&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; debugger&nbsp; &nbsp; };&nbsp; &nbsp; img.onerror = () => {&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; error: true&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; };&nbsp; &nbsp; // This line will fire a request for the image file&nbsp; &nbsp; img.src = this.props.imgSrc&nbsp; }进而&nbsp; background-image: url(${props => !props.loaded || props.error&nbsp; &nbsp;? `https://fallback.url`&nbsp; &nbsp;: props.imgSrc&nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript