我试图计算画廊中图像的大小,以使所有图像都适合屏幕,没有空白。 但是,调整窗口大小时,图像无法很好地拟合,并且有空白。
如果有人看到了什么问题,我想寻求帮助。 Tnx。
class Gallery extends React.Component {
static propTypes = {
tag: PropTypes.string
};
constructor(props) {
super(props);
this.state = {
images: [],
galleryWidth: this.getGalleryWidth()
};
}
getGalleryWidth(){
try {
return document.body.clientWidth;
} catch (e) {
return 1000;
}
}
componentDidMount() {
this.getImages(this.props.tag);
this.setState({
galleryWidth: document.body.clientWidth
});
}
render() {
return (
<div className="gallery-root">
{this.state.images.map(dto => {
return <Image key={'image-' + dto.id} dto={dto} galleryWidth={this.state.galleryWidth}/>;
})}
</div>
);
}
}
class Image extends React.Component {
static propTypes = {
dto: PropTypes.object,
galleryWidth: PropTypes.number
};
constructor(props) {
super(props);
this.calcImageSize = this.calcImageSize.bind(this);
this.state = {
size: 200
};
}
calcImageSize() {
const {galleryWidth} = this.props;
const targetSize = 200;
const imagesPerRow = Math.round(galleryWidth / targetSize);
const size = (galleryWidth / imagesPerRow);
this.setState({
size
});
}
componentDidMount() {
this.calcImageSize();
}
render() {
return (
<div
className="image-root"
style={{
backgroundImage: `url(${this.urlFromDto(this.props.dto)})`,
width: this.state.size + 'px',
height: this.state.size + 'px'
}}
>
</div>
);
}
}
.gallery-root {
text-align: center;
}
.gallery-header {
background-color: #222;
padding: 10px;
color: white;
font-size: 20pt;
}
.gallery-intro {
font-size: 15pt;
}
.image-root {
background-size: cover;
background-position: center center;
display: inline-block;
vertical-align: top;
box-sizing: border-box;
position: relative;
border: 1px solid white;
> div {
visibility: hidden;
background: rgba(0, 0, 0, 0.7);
cursor: pointer;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
color: white;
padding: 15px;
text-align: center;
text-align: center;
box-sizing: border-box;
white-space: pre;
display: flex;
align-items: center;
justify-content: center;
}
}