我有一个带有main
且带有overflow: auto
标签的组件。根据滚动高度,我需要渲染一个不同的元素。如何在React中获得元素滚动位置?
基本要点是这样:
function App() {
return (
<div>
<main
style={{
backgroundColor: "red",
overflow: "auto",
height: "500px",
padding: "5px"
}}
>
Please Track Me!
<div
style={{ backgroundColor: "blue", color: "white", height: "5000px" }}
>
Inner
</div>
</main>
</div>
);
}
我需要以某种方式跟踪main
(使用overflow: auto
)的滚动位置。
您的主要组件必须具有参考。https://reactjs.org/docs/refs-and-the-dom.html另外,您将在组件中使用一个名为onScroll的事件来更新它。检查一下
class ScrollAwareDiv extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
this.state = {scrollTop: 0}
}
onScroll = () => {
const scrollY = window.scrollY //Don't get confused by what's scrolling - It's not the window
const scrollTop = this.myRef.current.scrollTop
console.log(`onScroll, window.scrollY: ${scrollY} myRef.scrollTop: ${scrollTop}`)
this.setState({
scrollTop: scrollTop
})
}
render() {
const {
scrollTop
} = this.state
return (
<div
ref={this.myRef}
onScroll={this.onScroll}
style={{
border: '1px solid black',
width: '600px',
height: '100px',
overflow: 'scroll',
}} >
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
<p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
<p>ScrollTop is {scrollTop}</p>
</div>
)
}
}
ReactDOM.render(
<ScrollAwareDiv />,
document.getElementById('root')
);