javascript - 是否可以使用 react-lazyload 延迟加载背景图像

标签 javascript html css reactjs lazy-loading

我创建了一个 Section 组件,它将图像作为属性,并将其子项作为要在该部分中显示的内容,因此该组件将如下所示...

<Section image={'path/to/image'}>
 //content
</Section>

该组件将采用图像属性并将其设置为背景图像样式的 url...

let sectionStyle = {
  backgroundImage: `url(${this.props.image})`
}

然后将在返回元素中处理...

return (
  <section
    style={this.props.image ? sectionStyle : null}>
    <div>
      {this.props.children}
    </div>
  </section>
)

我的问题是,是否可以在不影响 SEO 内容可用性的情况下延迟加载背景图像?换句话说,我想避免延迟加载整个部分,但不知何故只是延迟加载与该部分关联的图像。

最佳答案

@naoise-golden 的回答的更新版本

import PropTypes from 'prop-types';
import React from 'react';

export default class LazyImage extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      src: null,
    };
  }

  componentDidMount () {
    const { src } = this.props;
    console.log('LazyImage componentDidMount props:', this.props);

    const imageLoader = new Image();
    imageLoader.src = src;

    imageLoader.onload = () => {
      console.log('LazyImage loaded src:', src);
      this.setState({ src });
    };
  }

  render () {
    const { placeholder, className, height, width, alt } = this.props;
    const { src } = this.state;
    return (
      <img src={src || placeholder} className={className} height={height} width={width} alt={alt} />
    );
  }
}

LazyImage.propTypes = {
  src: PropTypes.string,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  height: PropTypes.number,
  width: PropTypes.number,
  alt: PropTypes.string,
};

关于javascript - 是否可以使用 react-lazyload 延迟加载背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38326025/

相关文章:

jquery - 左对齐画廊的最后一行

javascript - 选择子元素(输入字段)时更改父 div 的 CSS

javascript - 拦截点击时,如何检测嵌套在 anchor 内的内容的点击?

html - CSS : border-radius and color not respected within table

javascript - 如何在单击 li 时显示 li 的边框

css - 如何使用 cakePHP 在 css 中添加媒体 ='screen'?

javascript - 条形顶部的值不随条形移动

javascript - 比较两个玩家分数数组,看看谁在列表中上升/下降

javascript - 为什么此代码在 chrome、firefox 等中不起作用?

html - 根据浏览器大小对齐图像