我创建了一个 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/