簡體   English   中英

如何通過 VariableSizeList 的行索引動態計算行高?

[英]How can I dynamically calculate row height by row index for VariableSizeList?

我需要通過 react-window 庫呈現長列表。 我不能確定所有行的大小都相同,因此它迫使我使用 VariableSizeList。 那么當您只知道要呈現的行索引和實際數據時,有沒有辦法計算行高?

我認為有可能以某種方式呈現它對最終用戶不可見並從中獲取高度,但我不確定它是否正確。

Yes 當使用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' }} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM