React onScroll不从父组件开火
问题描述:
我有一个父组件,它一开始没有高度,但会随着子组件的增加而增长。添加子元素后,我可以上下滚动,但是我注意到handleScroll函数没有被触发。React onScroll不从父组件开火
任何人都有类似的问题?
constructor() {
super();
this.handleScroll = this.handleScroll.bind(this);
}
handleScroll(e) {
console.log(e);
}
render() {
return (
<div className="parent" onScroll={this.handleScroll}>
{
this.props.children.map((child)=>{
<div>{child.name}</div>
})
}
)
}
答
您可以通过这样的滚动功能绑定到DIV:
import ReactDOM from 'react-dom';
// ...
constructor() {
super();
this.handleScroll = this.handleScroll.bind(this);
}
componentDidMount() {
const div = ReactDOM.findDOMNode(this.refs.someRef)
div.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
const div = ReactDOM.findDOMNode(this.refs.someRef)
div.removeEventListener('scroll', this.handleScroll);
}
handleScroll(e) {
console.log(e);
}
render() {
return (
<div ref="someRef" className="parent">
{
this.props.children.map((child)=>{
<div>{child.name}</div>
})
}
</div>
)
}
..和也请同时设置CSS为您的DIV为:
.parent{
overflow-y: auto;
}
什么你的'div.parent'风格?它是否包含“overflow:scroll;”属性并且在渲染时确实溢出了? –