React项目中使用ZingTouch时出现addEventListener()错误
ZingTouch绑定rotate事件报错
t.addEventListener is not a function解决方法 错误根源
document.getElementsByClassName('wheel')返回的是HTMLCollection(类数组对象),而ZingTouch的Region构造函数和bind方法都要求传入单个DOM元素,不是元素集合。这就导致内部调用addEventListener时触发错误——集合对象并没有这个方法。
两种修复方案
方案1:从元素集合中提取单个元素
修改componentDidMount内的代码,直接取集合的第一个匹配元素:
componentDidMount(){ const wheel = document.getElementsByClassName('wheel')[0]; const region = new ZingTouch.Region(wheel); region.bind(wheel, 'rotate', (e)=>{ console.log('rotating', e); }) }
方案2:使用React Refs(更符合React最佳实践)
用React内置的Ref机制直接获取组件内的DOM元素,避免直接操作DOM的潜在问题:
import React from 'react'; import "./Wheel.css"; import ZingTouch from "zingtouch"; class Wheel extends React.Component { wheelRef = React.createRef(); componentDidMount(){ const wheel = this.wheelRef.current; const region = new ZingTouch.Region(wheel); region.bind(wheel, 'rotate', (e)=>{ console.log('rotating', e); }) } render() { return ( <div className="wheel" ref={this.wheelRef}> <span className="menu-button">MENU</span> <button className="select-button">SELECT</button> <span className="material-symbols-outlined play-pause">play_pause</span> <span className="material-symbols-outlined fast-forward"> fast_forward </span> <span className="material-symbols-outlined fast-rewind"> fast_rewind </span> </div> ); } } export default Wheel;
额外说明
- 若页面存在多个
.wheel元素,方案1需确保索引对应目标元素;方案2的Ref是组件实例独立的,不会出现混淆问题。 - 你尝试的
addEventListener('click')报错也是同一原因:给元素集合而非单个DOM元素绑定事件,集合没有该方法。
内容的提问来源于stack exchange,提问作者Rimjhim Shrivastava
相关产品推荐
相关产品推荐

