How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

前端 未结 13 2261
旧时难觅i
旧时难觅i 2020-11-28 04:23

How can you achieve either a hover event or active event in ReactJS when you do inline styling?

I\'ve found that the onMouseEnter, onMouseLeave approach is buggy, so

13条回答
  •  北海茫月
    2020-11-28 04:49

    I had a similar issue when onMouseEnter was called but sometimes the corresponding onMouseLeave event wasn't fired, here is a workaround that works well for me (it partially relies on jQuery):

    var Hover = React.createClass({
        getInitialState: function() {
            return {
                hover: false
            };
        },
        onMouseEnterHandler: function(e) {
            this.setState({
                hover: true
            });
            console.log('enter');
    
            $(e.currentTarget).one("mouseleave", function (e) {
                this.onMouseLeaveHandler();
            }.bind(this));
    
        },
        onMouseLeaveHandler: function() {
            this.setState({
                hover: false
            });
            console.log('leave');
        },
        render: function() {
            var inner = normal;
            if(this.state.hover) {
                inner = hover;
            }
    
            return (
                
    {this.props.children}
    ); } });

    See on jsfiddle: http://jsfiddle.net/qtbr5cg6/1/


    Why was it happening (in my case): I am running a jQuery scrolling animation (through $('#item').animate({ scrollTop: 0 })) when clicking on the item. So the cursor doesn't leave the item "naturally", but during a the JavaScript-driven animation ... and in this case the onMouseLeave was not fired properly by React (React 15.3.0, Chrome 51, Desktop)

提交回复
热议问题