回答
雑な書き捨てコードですが、こんな感じで出来ます。
キャプチャー画像(animation Gif)
=> animation Gif
コード(React 16.3以前)
import React, { Component } from "react";
import ReactDOM from "react-dom";
import throttle from 'lodash.throttle';
class App extends Component {
state = {
scrollTop: 0
}
handleScroll = throttle((event) => {
this.setState({
scrollTop: this.node.scrollTop
})
}, 100)
render() {
return (
<div>
<div
style={{
overflowY: 'scroll',
height: '50px',
backgroundColor: '#ccc'
}}
onScroll={this.handleScroll}
ref={(node) => this.node = node}
>
<p style={{ fontSize: '50px' }}>Hello World</p>
</div>
<p>Scroll Top: {this.state.scrollTop}</p>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
=> Demo
コード(React 16.3以降)
import React, { Component } from "react";
import ReactDOM from "react-dom";
import throttle from 'lodash.throttle';
class App extends Component {
constructor(props) {
super(props);
this.node = React.createRef();
}
state = {
scrollTop: 0
}
handleScroll = throttle((event) => {
this.setState({
scrollTop: this.node.scrollTop
})
}, 100)
render() {
return (
<div>
<div
style={{
overflowY: 'scroll',
height: '50px',
backgroundColor: '#ccc'
}}
onScroll={this.handleScroll}
ref={this.node}
>
<p style={{ fontSize: '50px' }}>Hello World</p>
</div>
<p>Scroll Top: {this.state.scrollTop}</p>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
=> Demo
追記
import throttle from 'lodash.throttle';
//(中略)
handleScroll = throttle((event) => {
this.setState({
scrollTop: this.node.scrollTop
})
}, 100)
scrollする度に処理を走らせてしまうのはパフォーマンス的にしんどいので、100ミリ秒毎に処理を走らせるようにlodash
のthrottle
でscroll
イベントを間引きました。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/03 13:31
2018/07/03 13:45
2018/07/03 14:15
2018/07/04 02:09