是否可以通过react-lazyload延迟加载背景图像 [英] Is it possible to lazy load background images with react-lazyload
问题描述
我已经创建了一个Section组件,该组件将图像作为属性,并将其子代作为要在该部分中显示的内容,因此该组件将如下所示...
I have created a Section component which will take in an image as a property and its children as content to be displayed within the section, so the component would look as follows...
<Section image={'path/to/image'}>
//content
</Section>
该组件将使用image属性并将其设置为背景图片样式的网址...
The component will take the image property and set it as a url for background-image style...
let sectionStyle = {
backgroundImage: `url(${this.props.image})`
}
然后将在返回元素中对其进行处理...
which will then be processed in the return element...
return (
<section
style={this.props.image ? sectionStyle : null}>
<div>
{this.props.children}
</div>
</section>
)
我的问题是,是否可以在不损害SEO内容可用性的情况下延迟加载背景图片?换句话说,我要避免LazyLoading整个Section,但是以某种方式LazyLoad只是与该Section相关联的图像.
My question is, is it possible to Lazyload the background image whilst also not compromising the contents availability for SEO? in other words i want to avoid LazyLoading the entire Section, but somehow LazyLoad just the image associated with the Section.
推荐答案
@ naoise-golden的答案的更新版本
An updated version of @naoise-golden 's answer
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,
};
这篇关于是否可以通过react-lazyload延迟加载背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!