首页 > 解决方案 > 反应,事件功能很少

问题描述

有脚本 - 在 onMouseOver 事件期间图片增加,在 onMouseOut 期间 - 减少。同样在 onMouseOver 期间,z-index 发生变化(从 0 到 10),增加的图片位于其他图片之上。 https://jsfiddle.net/Nata_Hamster/k089ysxw/

但是在 onMouseOver 期间设置 z-index 的更改是错误的决定,因为在 onMouseOut 期间 z-index 变为 0。我看到下一个决定 - 通过单独的函数更改 z-index,例如悬停,并将其添加到两者事件。

但我做错了 - 意外的令牌

onMouseOver={(this, id)=>{this.increase.bind; this.hover.bind}}

https://jsfiddle.net/Nata_Hamster/knrw67py/ 如何正确地将两个函数添加到一个事件?

标签: reactjsfunctionevents

解决方案


您不能this用作参数名称,它是保留字。不过,您不需要使用它,因为箭头函数会自动绑定this到周围的上下文。因此,将其取出将使您的功能正常工作:

onMouseOver={(id)=>{this.increase.bind; this.hover.bind}}

编辑

看着你的小提琴,你似乎错误地调用了这些方法。这将解决它:

class Article extends React.Component {
  // Rest of your component ommitted for brevity

  render() {
    const TipStyle = {
      marginBottom: "10px"
    };

    return (
      <div style={TipStyle}>
        <h2 style={{ marginBottom: "1px" }}>{this.props.name}</h2>
        <div>
          {[1, 2, 3].map(id => {
            return (
              <img
                style={this.getImgStyle(id)}
                src={this.props[`img${id}`]}
                onMouseOver={() => {
                  this.increase(id);
                  this.hover(id);
                }}
                onMouseOut={() => {
                  this.increase(id);
                }}
              />
            );
          })}
          <pre>{JSON.stringify(this.state)}</pre>
        </div>
      </div>
    );
  }
}

推荐阅读