javascript - React 中的砌体网格
问题描述
根据这篇文章,我正在尝试实现一种砖石风格的网格。我想在 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;
}
解决方案
推荐阅读
- r - 最后使用 plotly() 时隐藏 scale_color_manual() 中的特定图例
- c++ - 使用 rdkafkacpp.h 的 C++ 中的基本 Kafka Consumer
- avfoundation - 在 iOS 上安排音频样本播放
- sequelize.js - 为什么 Sequelize 会创建一个名为“文本”的数据库列,而不是以模型属性命名
- assembly - 将索引寄存器分配给通用寄存器
- python - 使用numpy时相应地迭代2个数组的最佳方法是什么?
- css - 如何制作灵活的网格 css/react
- css-selectors - 通过 css-selector 或 xpath 在 DOM 中查找部分文本
- c# - 使用 Newtonsoft JSON 指定要编码和解码的属性和字段
- ios - 将带有相机叠加层的 CMSampleBufferGetImageBuffer 裁剪为 UIImage