簡體   English   中英

使用React,如何在可滾動div中水平滾動到所選項目?

[英]With React, how can I horizontally scroll to the selected item in a scrollable div?

想法是要有一個水平可滾動列表,選擇一個項目時,列表會滾動到該項目,這應使該項目在列表中居中。

我試圖使用React創建一個示例,但是我很難計算出scrollLeft值。

http://jsfiddle.net/remisture/zug42kh8/

const scrollContainer = ReactDOM.findDOMNode(this.scrollRef);
const activeItem = ReactDOM.findDOMNode(this.activeRef);

const scrollRect = scrollContainer.getBoundingClientRect();
const activeRect = activeItem.getBoundingClientRect();
const activeWidth = activeRect.width;
const activeLeft = activeRect.left;
const activeRight = activeRect.right;
const scrollWidth = scrollContainer.scrollWidth;
const scrollLeft = scrollRect.left;

scrollContainer.scrollLeft = (scrollWidth / 2) + (activeLeft / 2) + (scrollLeft * 2);

所需結果:

在此處輸入圖片說明

的jsfiddle

首先,是的,計算:

scrollLeftPosition: activeRect.left - scrollRect.left - (scrollRect.width / 2) + (activeRect.width / 2)

第二。 我將scrollLeft的操作更改為“ + =“。 因為您不應該只是根據情況分配,還應該考慮當前的滾動狀態。

scrollContainer.scrollLeft += this.state.scrollLeftPosition;

要點:在應用新狀態之前,您調用了this.centerActiveItem()。 this.setState是異步函數。 更新狀態后,您需要傳遞函數來調用它。

this.setState({}, callback);

暫無
暫無

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

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