首页 > 解决方案 > 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;
}

标签: javascriptcssreactjs

解决方案


推荐阅读