我有一个聊天小部件,每当我向上滚动时,它就会弹出一个消息数组。我现在面临的问题是,当消息加载时,滑块固定在顶部。我想让它关注上一个数组的最后一个索引元素。我发现我可以通过传递索引来进行动态引用,但我也需要知道使用哪种滚动函数来实现这一点

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

  render() {

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

当前回答

您可以使用componentDidUpdate之类的东西

componentDidUpdate() {
  var elem = testNode //your ref to the element say testNode in your case; 
  elem.scrollTop = elem.scrollHeight;
};

其他回答

对我有用的是:

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef(); // Create a ref    
    }

    // Scroll to ref function
    scrollToMyRef = () => {
        window.scrollTo({
            top:this.myRef.offsetTop, 
            // behavior: "smooth" // optional
        });
    };

    // On component mount, scroll to ref
    componentDidMount() {
        this.scrollToMyRef();
    }

    // Render method. Note, that `div` element got `ref`.
    render() {
        return (
            <div ref={this.myRef}>My component</div>
        )
    }
}

还可以使用scrollIntoView方法滚动到给定元素。

handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
 if (some_logic){
  tesNode.scrollIntoView();
  }
 }

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

你现在可以从react钩子API中使用useRef了

https://reactjs.org/docs/hooks-reference.html#useref

宣言

let myRef = useRef()

组件

<div ref={myRef}>My Component</div>

Use

window.scrollTo({ behavior: 'smooth', top: myRef.current.offsetTop })
 <div onScrollCapture={() => this._onScrollEvent()}></div>

 _onScrollEvent = (e)=>{
     const top = e.nativeEvent.target.scrollTop;
     console.log(top); 
}

你可以使用useRef和scrollIntoView。

使用useReffor你想滚动到的元素:这里我想滚动到PieceTabs元素,这就是为什么我用一个盒子(div)包装它,这样我就可以访问dom元素

您可能对refs很熟悉,它主要是作为一种访问DOM的方式。如果你传递一个ref对象给React, React会在相应的DOM节点发生变化时将其.current属性设置为相应的DOM节点。看医生

...
const tabsRef = useRef()
...
<Box ref={tabsRef}>
   <PieceTabs piece={piece} value={value} handleChange={handleChange} />
</Box>
...

创建一个处理滚动的函数:

  const handleSeeCompleteList = () => {
    const tabs = tabsRef.current
    if (tabs) {
      tabs.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      })
    }
  }

当你点击滚动到目标时,在你想要的元素上调用这个函数:

 <Typography
  variant="body2"
  sx={{
    color: "#007BFF",
    cursor: "pointer",
    fontWeight: 500,
  }}
  onClick={(e) => {
    handleChange(e, 2);
    handleSeeCompleteList(); // here we go
  }}
>
  Voir toute la liste
</Typography>;

好了