如何滚动到一个元素? [英] How to scroll to an element?
问题描述
我有一个聊天小部件,每次我向上滚动时,它都会拉出一系列消息.我现在面临的问题是,在加载消息时,滑块会固定在顶部.我希望它集中在上一个数组的最后一个索引元素上.我发现可以通过传递索引来创建动态引用,但是我还需要知道使用哪种滚动功能来实现
I have a chat widget that pulls up an array of messages every time I scroll up. The problem I am facing now is the slider stays fixed at the top when messages load. I want it to focus on the last index element from the previous array. I figured out that I can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
推荐答案
反应16.8 +,功能组件
import React, { useRef } from 'react'
const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop)
// General scroll to element function
const ScrollDemo = () => {
const myRef = useRef(null)
const executeScroll = () => scrollToRef(myRef)
return (
<>
<div ref={myRef}>I wanna be seen</div>
<button onClick={executeScroll}> Click to scroll </button>
</>
)
}
class ReadyToScroll extends Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
render() {
return <div ref={this.myRef}></div>
}
scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)
// run this method to execute scrolling.
}
类组件-引用回调
class ReadyToScroll extends Component {
myRef=null
// Optional
render() {
return <div ref={ (ref) => this.myRef=ref }></div>
}
scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)
// run this method to execute scrolling.
}
请勿使用字符串引用.
字符串引用损害性能,不可组合,并且即将淘汰(2018年8月).
Don't use String refs.
String refs harm performance, aren't composable, and are on their way out (Aug 2018).
字符串引用存在一些问题,被认为是旧问题,并且很可能会 在将来的版本之一中被删除. [React官方文档]
string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. [Official React documentation]
资源1
我们希望将ref附加到dom元素上,而不是附加到react组件上.因此,当将其传递给子组件时,我们无法命名prop ref.
We want the ref to be attached to a dom element, not to a react component. So when passing it to a child component we can't name the prop ref. 然后将ref属性附加到dom元素上. Then attach the ref prop to a dom element. 这篇关于如何滚动到一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!将参考传递给孩子
Passing ref to a child
const MyComponent = () => {
const myRef = useRef(null)
return <ChildComp refProp={myRef}></ChildComp>
}
const ChildComp = (props) => {
return <div ref={props.refProp} />
}