gpt4 book ai didi

javascript - 如何滚动到一个元素?

转载 作者:IT王子 更新时间:2023-10-29 02:45:08 25 4
gpt4 key购买 nike

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

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

render() {

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

最佳答案

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>
</>
)
}

Click here for a full demo on 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 月)。

string refs have some issues, are considered legacy, and are likely tobe removed in one of the future releases. [Official React documentation]

resource1 resource2

可选:平滑滚动动画

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

将 ref 传递给 child

我们希望 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} />
}

关于javascript - 如何滚动到一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com