如何滚动到一个元素?

新手上路,请多包涵

我有一个聊天小部件,每次向上滚动时都会拉出一系列消息。我现在面临的问题是消息加载时滑块固定在顶部。我希望它专注于前一个数组中的最后一个索引元素。我发现我可以通过传递索引来制作动态引用,但我还需要知道使用哪种滚动函数来实现这一点

 handleScrollToElement(event) {
    const tesNode = ReactDOM.findDOMNode(this.refs.test)
    if (some_logic){
      //scroll to testNode
    }
  }

  render() {

    return (
      <div>
        <div ref="test"></div>
      </div>)
  }

原文由 edmamerto 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 837
2 个回答
<div id="componentToScrollTo"><div>

 <a href='#componentToScrollTo'>click me to scroll to this</a>

这就是你所需要的。

原文由 Robert O‘Toole 发布,翻译遵循 CC BY-SA 4.0 许可协议

React 16.8 +,功能组件

const ScrollDemo = () => {
   const myRef = useRef(null)

   const executeScroll = () => myRef.current.scrollIntoView()
   // run this function from an event handler or an effect to execute scroll

   return (
      <>
         <div ref={myRef}>Element to scroll to</div>
         <button onClick={executeScroll}> Click to scroll </button>
      </>
   )
}

单击此处查看有关 StackBlits 的完整演示

React 16.3 +,类组件

class ReadyToScroll extends Component {
    constructor(props) {
        super(props)
        this.myRef = React.createRef()
    }

    render() {
        return <div ref={this.myRef}>Element to scroll to</div>
    }

    executeScroll = () => this.myRef.current.scrollIntoView()
    // run this method to execute scrolling.
}

类组件 - Ref 回调

class ReadyToScroll extends Component {
    render() {
        return <div ref={ (ref) => this.myRef=ref }>Element to scroll to</div>
    }

    executeScroll = () => this.myRef.scrollIntoView()
    // run this method to execute scrolling.
}


不要使用字符串引用。

字符串引用会损害性能,不可组合,并且即将被淘汰(2018 年 8 月)。

字符串引用有一些问题,被认为是遗留的,并且可能会在未来的版本之一中被删除。 [官方 React 文档]

资源 1 资源 2

可选:平滑滚动动画

/* css */
html {
    scroll-behavior: smooth;
}

将 ref 传递给孩子

我们希望 ref 附加到 dom 元素,而不是 react 组件。因此,当将它传递给子组件时,我们不能将 prop 命名为 ref。

 const MyComponent = () => {
    const myRef = useRef(null)
    return <ChildComp refProp={myRef}></ChildComp>
}

然后将 ref 属性附加到 dom 元素。

 const ChildComp = (props) => {
    return <div ref={props.refProp} />
}

原文由 Ben Carp 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题