How can I scroll a div to be visible in ReactJS?

前端 未结 9 1544
梦如初夏
梦如初夏 2020-12-04 15:25

I have a popup list which is a div that contains a vertical list of child divs. I have added up/down keyboard navigation to change which child is

9条回答
  •  误落风尘
    2020-12-04 16:07

    To build on @Michelle Tilley's answer, I sometimes want to scroll if the user's selection changes, so I trigger the scroll on componentDidUpdate. I also did some math to figure out how far to scroll and whether scrolling was needed, which for me looks like the following:

      componentDidUpdate() {
        let panel, node;
        if (this.refs.selectedSection && this.refs.selectedItem) {
          // This is the container you want to scroll.          
          panel = this.refs.listPanel;
          // This is the element you want to make visible w/i the container
          // Note: You can nest refs here if you want an item w/i the selected item          
          node = ReactDOM.findDOMNode(this.refs.selectedItem);
        }
    
        if (panel && node &&
          (node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {
          panel.scrollTop = node.offsetTop - panel.offsetTop;
        }
      }

提交回复
热议问题