2

I need to render long list via react-window library. I can't be sure that all rows will be the same size so it forces me to use VariableSizeList. So is there a way to calculate row height when you know only index of row and actual data to be rendered?

I think it's possible to render it somehow not visible to the end user and get height from but I'm not sure is it the right way.

4

1 回答 1

1

是,当使用VariableSizeList指定itemSize函数时。

例如

itemSize = {(i) => onGetItemSize(rows[i])}

onGetItemSize 通过以下方式测量内容:

  1. 如果内容很小,则返回单个行高。
  2. 将内容写入一个空元素,其宽度和属性与您的行相同。然后测量元件高度,然后再次清空元件。

例如:

 onGetItemSize={((row) =>
                {
                let text = row.original.text;
                // if no text, or text is short, don't bother measuring.
                if (!text || text.length < 15)
                    return rowHeight;

                // attempt to measure height by writting text to a, kind of hidden element.
                let hiddenElement = document.getElementById(this.hiddenFieldName());
                if (hiddenElement)
                {
                    hiddenElement.textContent = text;
                    let ret = hiddenElement.offsetHeight;
                    hiddenElement.textContent = '';

                    if (ret > 0)
                        return Math.max(ret, rowHeight);
                }

                // fallback
                return rowHeight;
            })}

然后在 DOM 中的适当位置包含这个空元素。

<div id={this.hiddenFieldName()} style={{ visibility: 'visible', whiteSpace: 'normal' }} />
于 2020-09-09T17:05:44.820 回答