代码之家  ›  专栏  ›  技术社区  ›  Remi Sture

使用react,如何在可滚动分区中水平滚动到所选项目?

  •  0
  • Remi Sture  · 技术社区  · 8 年前

    其思想是要有一个水平可滚动的列表,当选择一个项目时,该列表滚动到该项目,该项目应在列表中居中。

    我曾尝试使用react创建一个示例,但我很难计算出

    http://jsfiddle.net/remiture/zug42kh8/

    const scrollcontainer=reactdom.finddomnode(this.scrollRef);
    const activeitem=reactdom.finddomnode(this.activeref);
    
    const scrollrect=scrollContainer.getboundingclientrect();
    const activestubte=activeitem.getboundingclientrect();
    const activewidth=activ勃起.width;
    const activeleft=活动直立。左;
    const activeteright=活动直立.right;
    const scrollwidth=滚动容器.scrollwidth;
    const scrolleft=向左滚动;
    
    ScrollContainer.ScrollLeft=(ScrollWidth/2)+(ActiveLeft/2)+(ScrollLeft*2);
    

    预期结果:

    .

    我试图用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);
    

    预期结果:

    1 回复  |  直到 8 年前
        1
  •  1
  •   Persijn    8 年前

    JSFiddle

    首先,是的,计算:

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

    第二个。我把ScrollLeft的操作改为“+=”。因为您不应该只分配在您的情况下,但考虑到当前滚动状态。

    scrollContainer.scrollLeft += this.state.scrollLeftPosition;
    

    要点是:您在应用新状态之前调用了这个.centerActiveItem()。setState是异步函数。更新状态后需要传递函数来调用它。

    this.setState({}, callback);