反应悬停以显示图像。悬停不起作用

时间:2016-06-17 22:50:57

标签: javascript reactjs

仍在努力学习React。我正试图在你悬停时显示图像。这是我的Item组件。

import React from 'react';


import Eyecon from '../../static/eye.svg';


class Item extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'Item';
        this.state = {
            hover: false
        };
    }
    mouseOver() {
        this.setState({hover: true});
    }
    mouseOut() {
        this.setState({hover: false});
    }
    render() {
      const { item, i } = this.props;
        return (
            <div className="grid-box" onMouseOver={this.mouseOver} onMouseOut={this.mouseOut}>
            {this.state.hover ? (<img src={Eyecon}/>) : null}       
            </div>
        )
    }
}


export default Item;

我怎样才能这样做只有我悬停在上面的项目会显示图像?

3 个答案:

答案 0 :(得分:1)

这只是一个&#39;这个&#39;约束问题。将console.log放在mouseOver和mouseOut方法中,你会发现你的状态并没有改变。

有许多方法可以绑定&#39;这个&#39;类方法中的上下文。在这个例子中,我将向您展示三种方法(不要做所有三种方法,只选择一种方法)。

import React from 'react';
import Eyecon from '../../static/eye.svg';

class Item extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'Item';
        // 1. bind your functions in the constructor.
        this.mouseOver = this.mouseOver.bind(this);
        this.mouseOut = this.mouseOut.bind(this);
        this.state = {
            hover: false
        };
    }

    // 2. bind it with fat arrows.
    mouseOver = () => {
        this.setState({hover: true});
    }
    mouseOut() {
        this.setState({hover: false});
    }
    render() {
      const { item, i } = this.props;
        // 3. bind them in the render method (not recommended for performance reasons)
        return (
            <div className="grid-box" onMouseOver={this.mouseOver.bind(this)} onMouseOut={this.mouseOut.bind(this)}>
            {this.state.hover ? (<img src={Eyecon}/>) : null}       
            </div>
        )
    }
}


export default Item;

以下是对不同方法的解释,这个&#39;这个&#39;使用ES6类进行反应的上下文: http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html

答案 1 :(得分:0)

也许是因为您必须绑定mouseOvermouseOut来调用才能在其中使用this.setState

替换:

<div className="grid-box" onMouseOver={this.mouseOver} onMouseOut={this.mouseOut}>

使用:

<div className="grid-box" onMouseOver={this.mouseOver.bind(this)} onMouseOut={this.mouseOut.bind(this)}>

答案 2 :(得分:0)

建议的其他解决方案完全有效,但您只需将功能转换为ES6 arrow functions即可轻松解决此问题。

  

与函数表达式相比,箭头函数表达式具有更短的语法,并且词汇绑定此值(不绑定它自己的this,arguments,super或new.target)。箭头功能始终是匿名的。

像这样:

mouseOver = () => {
  this.setState({hover: true});
}
mouseOut = () => {
  this.setState({hover: false});
}

简单。