我有一个聊天小部件,每当我向上滚动时,它就会弹出一个消息数组。我现在面临的问题是,当消息加载时,滑块固定在顶部。我想让它关注上一个数组的最后一个索引元素。我发现我可以通过传递索引来进行动态引用,但我也需要知道使用哪种滚动函数来实现这一点
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
2019年7月-专用钩子/函数
专用的钩子/函数可以隐藏实现细节,并为组件提供简单的API。
React 16.8 +功能组件
const useScroll = () => {
const elRef = useRef(null);
const executeScroll = () => elRef.current.scrollIntoView();
return [executeScroll, elRef];
};
在任何功能组件中使用它。
const ScrollDemo = () => {
const [executeScroll, elRef] = useScroll()
useEffect(executeScroll, []) // Runs after component mounts
return <div ref={elRef}>Element to scroll to</div>
}
完整的演示
React 16.3 +类组件
const utilizeScroll = () => {
const elRef = React.createRef();
const executeScroll = () => elRef.current.scrollIntoView();
return { executeScroll, elRef };
};
在任何类组件中使用它。
class ScrollDemo extends Component {
constructor(props) {
super(props);
this.elScroll = utilizeScroll();
}
componentDidMount() {
this.elScroll.executeScroll();
}
render(){
return <div ref={this.elScroll.elRef}>Element to scroll to</div>
}
}
完整的演示
最好的方法是使用element。scrollIntoView({behavior: 'smooth'})。这将以漂亮的动画将元素滚动到视图中。
当你将它与React的useRef()结合使用时,可以通过以下方式完成。
import React, { useRef } from 'react'
const Article = () => {
const titleRef = useRef()
function handleBackClick() {
titleRef.current.scrollIntoView({ behavior: 'smooth' })
}
return (
<article>
<h1 ref={titleRef}>
A React article for Latin readers
</h1>
// Rest of the article's content...
<button onClick={handleBackClick}>
Back to the top
</button>
</article>
)
}
当你想要滚动到React组件时,你需要将引用转发给渲染的元素。本文将深入探讨这个问题。
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.
}
类组件-引用回调
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文档]
resource1resource2
可选:平滑滚动动画
/* css */
html {
scroll-behavior: smooth;
}
传递ref给一个子对象
我们希望ref附加到一个dom元素,而不是一个react组件。所以当把它传递给子组件时,我们不能给prop ref命名。
const MyComponent = () => {
const myRef = useRef(null)
return <ChildComp refProp={myRef}></ChildComp>
}
然后将ref prop附加到dom元素上。
const ChildComp = (props) => {
return <div ref={props.refProp} />
}