React列表项的虚拟化位置

时间:2017-02-23 12:02:38

标签: javascript html css reactjs react-virtualized

我在类似的设置中使用React Virtualized,如下面的代码段。有几个项目使用CellMeasurer呈现。最后一项表示将加载更多项目并且未正常呈现。此项目的位置/样式错误,高度错误。我该如何解决这个问题?

如果你想玩它,这是一个Plunkr: https://plnkr.co/edit/TrKdNu4FfNsXqERPVnYo?p=preview

var List = ReactVirtualized.List;
var CellMeasurer = ReactVirtualized.CellMeasurer;
var CellMeasurerCache = ReactVirtualized.CellMeasurerCache;

var cache = new CellMeasurerCache({
  fixedWidth: true,
  minHeight: 50
});

// List data as an array of strings
var namesList = [
  'Brian Vaughn',
  'Bob Smith',
  'Someone Else',
  'I hate making up names for the sake of names.'
  // And so on...
];

var App = React.createClass({
  getInitialState: function() {
    return {
      list: namesList
    };
  },
  render: function() {
    return <List
    className='List'
    width={300}
    height={300}
    rowCount={this.state.list.length + 1}
    rowHeight={cache.rowHeight}
    deferredMeasurementCache={cache}
    list={this.state.list}
    rowRenderer={
      ({ index, isScrolling, key, parent, style }) => {
        var item = this.state.list[index];
        let result;
        if (!item) {
          console.log(index);
          result =
            <div className='Row'
          style={style}
          key={key}
            >Loading!!!
          </div>; }
        else
          result = <CellMeasurer
        cache={cache}
        columnIndex={0}
        key={key}
        style={style}
        rowIndex={index}
        parent={parent}>
          {

              <div
            className='Row'
            key={key}
            style={style}
              >
              {this.state.list[index]}
            </div>
          }
        </CellMeasurer>;
        return result;
      }}/>;
  }
});

// Render your list
ReactDOM.render(
  <App/>,
  document.getElementById('example')
);
.List {
  border: 1px solid black;
  box-sizing: border-box;
}
.Row {
  width: 100%;
  height: 100%;
  border-bottom: 1px solid black;
  display: flex;
  align-items: center;
  padding: 0 0.5rem;
  box-sizing: border-box;
}
<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/react/dist/react-with-addons.min.js"></script>
    <script src="https://unpkg.com/react-dom/dist/react-dom.min.js"></script>
    <script src="https://unpkg.com/react-virtualized/dist/umd/react-virtualized.js"></script>

    <link rel="stylesheet" href="https://unpkg.com/react-virtualized/styles.css">
    <link rel="stylesheet" href="styles.css">
  </head>

  <body>
    <div id="example">
      <!-- This element's contents will be replaced with your code... -->
    </div>
    <script src="script.js"></script>
  </body>

</html>

1 个答案:

答案 0 :(得分:1)

CellMeasurer不打算以这种方式仅用于某些行。从外部POV我理解为什么它看起来应该只是工作。

Grid呈现某个单元格时 - 如果它认为CellMeasurer正在使用 - 那么它positions the cell at top:0, left:0会在Grid / List内为其提供空间扩大。 (它的容器大小限制了它的大小,即使它绝对定位。我不确定为什么这是诚实的。)

所以在你的情况下,Grid看到最后一行没有被测量,认为它应该是,并将它定位在0,0。

现在最简单的解决方案是将该行包裹在CellMeasurer中。