我想检查某个特定元素在单击时是否具有指定的类。我知道你可以绑定一个传递e.target
给处理程序的点击处理程序。我的想法是去e.target.classList.indexOf(this.myClass) > -1
看看它是否有类,但我收到以下错误。
e.target.classList.indexOf 不是函数
我认为这是因为classList
是一个类似数组的对象,而不是实际的数组。有没有一种更简单的方法可以从 React 中单击的元素获取类列表,而无需执行所有“切片调用”魔法?
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myClass = 'my-class';
}
handleClick(e) {
// check if e.target class has this.myClass
if (/* logic */) {
// perform action
}
}
render() {
return <div onClick={this.handleClick.bind(this)} className={this.myClass + ' other-class'}>
<div>My Component</div>
</div>
}
}
如何从 React 事件系统中单击的“目标”元素获取类数组?