根据this的文章,我试图实现一种砌体样式的网格。我想在React组件中实现它。由于某些原因,样式不适用。我现在还很陌生,所以我不知道自己做错了什么。我现在遇到的问题是,我的JS似乎没有应用CSS。
React组件中的JS
// Also tried componentWillMount
componentDidMount = () => {
setTimeout(() => {
this.resizeAllGridItems();
}, 5000);
}
resizeGridItem = (item) => {
let grid = document.getElementsByClassName("masonry-grid")[0];
let rowHeight = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-auto-rows'));
let rowGap = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-row-gap'));
let rowSpan = Math.ceil((item.querySelector('.content').getBoundingClientRect().height+rowGap)/(rowHeight+rowGap));
item.style.gridRowEnd = "span "+rowSpan;
}
resizeAllGridItems = () => {
console.log('running..');
let allItems = document.getElementsByClassName("item");
for(let x=0; x< allItems.length; x++){
this.resizeGridItem(allItems[x]);
}
}
HTML
<div className="masonry-grid">
<div className="item one">
<div className="content">1</div>
</div>
<div className="item two">
<div className="content">2</div>
</div>
<div className="item three">
<div className="content">3</div>
</div>
<div className="item four">
<div className="content">4</div>
</div>
<div className="item five">
<div className="content">5</div>
</div>
<div className="item six">
<div className="content">6</div>
</div>
<div className="item seven">
<div className="content">7</div>
</div>
<div className="item eight">
<div className="content">8</div>
</div>
</div>
CSS
.masonry-grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(250px,1fr));
}
.masonry-grid--item {
}
.one {
height: 200px;
background-color: green;
}
.two {
height: 150px;
background-color: red;
}
.three {
height: 250px;
background-color: blue;
}
.four {
height: 200px;
background-color: yellow;
}
.five {
height: 220px;
background-color: grey;
}
.six {
height: 180px;
background-color: purple;
}
.seven {
height: 200px;
background-color: orange;
}
.eight {
height: 140px;
background-color: grey;
}