反应 onScroll 不起作用 [英] React onScroll not working
问题描述
我正在尝试将 onscroll 事件处理程序添加到特定的 dom 元素.看看这段代码:
class ScrollingApp 扩展 React.Component {..._handleScroll(ev) {console.log("滚动!");}componentDidMount() {this.refs.list.addEventListener('scroll', this._handleScroll);}componentWillUnmount() {this.refs.list.removeEventListener('scroll', this._handleScroll);}使成为() {返回 (<div ref="列表">{this.props.items.map( (item) => {return (<Item item={item}/>);})}
);}}
代码很简单,正如你所看到的,我想处理 div#list 滚动.当我运行这个例子时,它不起作用.所以我尝试直接在渲染方法上绑定 this._handleScroll ,它也不起作用.
... </div>所以我打开了 chrome 检查器,直接添加了 onscroll 事件:
document.getElementById('#list').addEventListener('scroll', ...);
它正在工作!我不知道为什么会发生这种情况.这是 React 的错误还是什么?还是我错过了什么?任何设备都将不胜感激.
解决方案 问题的根源在于 this.refs.list
是一个 React 组件,而不是一个 DOM 节点.要获取具有 addEventListener()
方法的 DOM 元素,您需要调用 ReactDOM.findDOMNode()
:
class ScrollingApp 扩展 React.Component {_handleScroll(ev) {console.log("滚动!");}componentDidMount() {const list = ReactDOM.findDOMNode(this.refs.list)list.addEventListener('scroll', this._handleScroll);}componentWillUnmount() {const list = ReactDOM.findDOMNode(this.refs.list)list.removeEventListener('scroll', this._handleScroll);}/* .... */}
I'm trying to add onscroll event handler to specific dom element. Look at this code:
class ScrollingApp extends React.Component {
...
_handleScroll(ev) {
console.log("Scrolling!");
}
componentDidMount() {
this.refs.list.addEventListener('scroll', this._handleScroll);
}
componentWillUnmount() {
this.refs.list.removeEventListener('scroll', this._handleScroll);
}
render() {
return (
<div ref="list">
{
this.props.items.map( (item) => {
return (<Item item={item} />);
})
}
</div>
);
}
}
Code is quite simple, and as you can see, I want to handle div#list scrolling. When I was running this example, it isn't working. So I tried bind this._handleScroll on render method directly, it doesn't work either.
<div ref="list" onScroll={this._handleScroll.bind(this)> ... </div>
So i opened chrome inspector, adding onscroll event directly with:
document.getElementById('#list').addEventListener('scroll', ...);
and it is working! I don't know why this happens. Is this a bug of React or something? or did I missed something? Any device will very appreciated.
解决方案 The root of the problem is that this.refs.list
is a React component, not a DOM node. To get the DOM element, which has the addEventListener()
method, you need to call ReactDOM.findDOMNode()
:
class ScrollingApp extends React.Component {
_handleScroll(ev) {
console.log("Scrolling!");
}
componentDidMount() {
const list = ReactDOM.findDOMNode(this.refs.list)
list.addEventListener('scroll', this._handleScroll);
}
componentWillUnmount() {
const list = ReactDOM.findDOMNode(this.refs.list)
list.removeEventListener('scroll', this._handleScroll);
}
/* .... */
}
这篇关于反应 onScroll 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文