这个想法是要有一个水平可滚动列表,选择一个项目时,列表会滚动到该项目,这应该使该项目在列表中居中。
我试图使用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);
所需结果:
答案 0 :(得分:1)
首先,是的,计算:
scrollLeftPosition: activeRect.left - scrollRect.left - (scrollRect.width / 2) + (activeRect.width / 2)
第二。我将scrollLeft的操作更改为“ + =“。您不仅应该根据情况分配,还应考虑当前的滚动状态。
scrollContainer.scrollLeft += this.state.scrollLeftPosition;
要点:您在应用新状态之前调用了this.centerActiveItem()。 this.setState是异步函数。更新状态后,您需要传递函数来调用它。
this.setState({}, callback);