[英]With React, how can I horizontally scroll to the selected item in a scrollable div?
The idea is to have a horizontal scrollable list, and when selecting an item, the list scrolls to that item, which should make the item centered in the list. 想法是要有一个水平可滚动列表,选择一个项目时,列表会滚动到该项目,这应使该项目在列表中居中。
I have tried to create an example using React, but I struggle to calculate the scrollLeft
value. 我试图使用React创建一个示例,但是我很难计算出
scrollLeft
值。
http://jsfiddle.net/remisture/zug42kh8/ 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);
Desired result: 所需结果:
First of all, yeah, calculating: 首先,是的,计算:
scrollLeftPosition: activeRect.left - scrollRect.left - (scrollRect.width / 2) + (activeRect.width / 2)
Second. 第二。 I changed manipulation with scrollLeft to "+=".
我将scrollLeft的操作更改为“ + =“。 As you should not just assign in your case, but take in account current scroll state.
因为您不应该只是根据情况分配,还应该考虑当前的滚动状态。
scrollContainer.scrollLeft += this.state.scrollLeftPosition;
And the main point: you called this.centerActiveItem() before new state applied. 要点:在应用新状态之前,您调用了this.centerActiveItem()。 this.setState is async function.
this.setState是异步函数。 You need to pass function to call it after updating state.
更新状态后,您需要传递函数来调用它。
this.setState({}, callback);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.