是否可以在没有滚动条/溢出的 react 元素上注册 onScroll 事件?
我希望通过鼠标滚轮滚动来缩放图片。 我试过了
<div style={{position: "relative", width: "100%", height:"100%"}} onScroll={ () => console.log("TEST")}>
这不会触发事件,onWheel 也不会。如果我将事件更改为 onClick 一切正常。
我知道这是可能的,因为有一个 React 组件可以使它工作,我尝试了 react 轮处理程序并且它工作了。但是当没有溢出或滚动条时,他们如何让它注册鼠标滚轮事件呢?
编辑:
当我手动将事件监听器添加到 componentDidMount 时,我得到了它的工作,这是我当前的组件。有没有办法让 onWheel 上的合成事件正常工作?我尝试将 onWheel 添加到 div 和 img 但它不会触发。
class Zoom extends Component {
state = {
size: 20,
}
componentDidMount() {
window.addEventListener('wheel', this.handleScroll, true);
}
handleScroll = e => {
e.preventDefault();
console.log(e)
if (e.deltaY > 0 && this.state.size < 50) {
this.setState({size: this.state.size + 1})
} else if (e.deltaY < 0 && this.state.size > 20) {
this.setState({size: this.state.size - 1})
}
}
render = () =>
<div className="livetods-product-image-container" style={{
top: openAsModal() ? '25%' : '20%',
left: openAsModal() ? '30%' : '',
right: openAsModal() ? '30%' : '',
width: this.state.size + "%"
}}>
<div className="livetods-product-image-button-container" >
<div></div>
<h6 className="livetods-product-image-name">{this.props.name}</h6>
<span className="livetods-modal-header-close-button" onClick={e => this.props.hideImage()}>×</span>
</div>
<div style={{position: "relative", width: "100%", height:"100%"}}>
<div style={{position: "absolute", padding: "5px"}}>
<FontAwesomeIcon icon={faSearchPlus} color={'red'} style={{ width: '20px', height: '20px', pointerEvents:"none"}}/>
</div>
<img src={this.props.src} style={{borderRadius: "5px"}}/>
</div>
</div>
}
最佳答案
使用onWheel
event and its properties而不是 onScroll
来达到相同的结果。
onScroll
事件不再 bubbles up在 react 。 This question非常相似。
onWheel
适用于触控板滚动和鼠标滚轮滚动。
Here是一个简单的示例,展示了 onWheel
使用您提供的代码示例。
更新:
我已经更改了codesanbox示例以反射(reflect)您的类组件。 onWheel
现在也可以使用了。您之前可能遇到的问题是这样的警告:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method `isPropagationStopped` on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See https://reactjs.org/docs/legacy-event-pooling.html for more information.
workaround将 e.persist()
添加到您的 onScroll 函数,如我的示例所示。
关于javascript - React元素中的鼠标滚轮/滚动事件没有溢出(图片缩放),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67986483/