我想在array.map函数中添加事件监听器onTouchStart,Move和End到img标签,因此它只捕获一个事件监听器(onTouchStart),但是如果我将这个监听器设置为div,并且class =“header-added-heroes “所有3个侦听器都工作,我读到将'this'绑定到array.map并且仅捕获onTouchStart,我将非常感谢有关此问题的任何信息。
{this.props.addedHeroes.map( function(el) {
return (<a name={el.link} key={uniqueId()} className="heroes__link">
<div className="hero"> {console.log(' map this : ', this === that)}
{
<img className="hero__image"
onTouchStart={this.onTouchStart}
onTouchMove={this.handleMove}
onTouchEnd={this.onTouchEnd}
src={el.image}
/>
}
</div>
</a>);
}, this )}
完整代码:
import React from "react";
import uniqueId from "lodash/uniqueId";
import HeroCounter from "../../images/HeroCounter.svg";
class HeaderAddedHeroes extends React.Component {
state = {
heroes: [1, 2, 3, 4],
showCloseButton: 0
};
constructor(props) {
super(props);
this.onTouchStart = this.onTouchStart.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
this.handleMove = this.handleMove.bind(this);
}
handleMove() {
console.log('moved');
this.setState({ showCloseButton: 1 })
}
onTouchStart() {
console.log('started');
this.setState({ showCloseButton: 2 })
}
onTouchEnd() {
console.log('ended');
this.setState({ showCloseButton: 3 })
}
render() { var that = this;
return (
<header className="header-added-heroes"> { console.log(' this : ', that)}
<div className="header-added-heroes"
onTouchMove={this.handleMove}
onTouchStart={ this.onTouchStart }
onTouchEnd={this.onTouchEnd}>
{ this.state.showCloseButton }
</div>
<div className="heroes">
{this.props.addedHeroes.map( function(el) {
return (<a name={el.link} key={uniqueId()} className="heroes__link">
<div className="hero"> {console.log(' map this : ', this === that)}
{
<img className="hero__image"
onTouchStart={this.onTouchStart}
onTouchMove={this.handleMove}
onTouchEnd={this.onTouchEnd}
src={el.image}
/>
}
</div>
</a>);
}, this )}
</header>
);
}
}
你总是可以使用箭头功能。
解决方案是:删除'uniqueId()'
{this.props.addedHeroes.map((el, i) => {
return (<a name={el.link} key={i} className="heroes__link">
<div className="hero">
<img className="hero__image"
onTouchStart={this.onTouchStart}
onTouchMove={this.handleMove}
onTouchEnd={this.onTouchEnd}
src={el.image}
/>
</div>
</a>);
}
)}