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

前端 未结 13 2253
旧时难觅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:44

    Have you tried any of these?

    onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp

    SyntheticEvent

    it also mentions the following:

    React normalizes events so that they have consistent properties across different browsers.

    The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture to the event name; for example, instead of using onClick, you would use onClickCapture to handle the click event in the capture phase.

    0 讨论(0)
  • 2020-11-28 04:44

    you can use onMouseOver={this.onToggleOpen} and onMouseOut={this.onToggleOpen} to muse over and out on component

    0 讨论(0)
  • 2020-11-28 04:47

    I've just bumped into this same problem when listening for onMouseLeave events on a disabled button. I worked around it by listening for the native mouseleave event on an element that wraps the disabled button.

    componentDidMount() {
        this.watchForNativeMouseLeave();
    },
    componentDidUpdate() {
        this.watchForNativeMouseLeave();
    },
    // onMouseLeave doesn't work well on disabled elements
    // https://github.com/facebook/react/issues/4251
    watchForNativeMouseLeave() {
        this.refs.hoverElement.addEventListener('mouseleave', () => {
            if (this.props.disabled) {
                this.handleMouseOut();
            }
        });
    },
    render() {
        return (
            <span ref='hoverElement'
                onMouseEnter={this.handleMouseEnter}
                onMouseLeave={this.handleMouseLeave}
            >
                <button disabled={this.props.disabled}>Submit</button>
            </span>
        );
    }
    

    Here's a fiddle https://jsfiddle.net/qfLzkz5x/8/

    0 讨论(0)
  • 2020-11-28 04:49

    Use Radium!

    The following is an example from their website:

    var Radium = require('radium');
    var React = require('react');
    var color = require('color');
    
    @Radium
    class Button extends React.Component {
      static propTypes = {
        kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired
      };
    
      render() {
        // Radium extends the style attribute to accept an array. It will merge
        // the styles in order. We use this feature here to apply the primary
        // or warning styles depending on the value of the `kind` prop. Since its
        // all just JavaScript, you can use whatever logic you want to decide which
        // styles are applied (props, state, context, etc).
        return (
          <button
            style={[
              styles.base,
              styles[this.props.kind]
            ]}>
            {this.props.children}
          </button>
        );
      }
    }
    
    // You can create your style objects dynamically or share them for
    // every instance of the component.
    var styles = {
      base: {
        color: '#fff',
    
        // Adding interactive state couldn't be easier! Add a special key to your
        // style object (:hover, :focus, :active, or @media) with the additional rules.
        ':hover': {
          background: color('#0074d9').lighten(0.2).hexString()
        }
      },
    
      primary: {
        background: '#0074D9'
      },
    
      warning: {
        background: '#FF4136'
      }
    };

    0 讨论(0)
  • 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 (
                <div style={outer}>
                    <div style={inner}
                        onMouseEnter={this.onMouseEnterHandler} >
                        {this.props.children}
                    </div>
                </div>
            );
        }
    });
    

    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)

    0 讨论(0)
  • 2020-11-28 04:50

    You can't with inline styling alone. Do not recommend reimplementing CSS features in JavaScript we already have a language that is extremely powerful and incredibly fast built for this use case -- CSS. So use it! Made Style It to assist.

    npm install style-it --save

    Functional Syntax (JSFIDDLE)

    import React from 'react';
    import Style from 'style-it';
    
    class Intro extends React.Component {
      render() {
        return Style.it(`
          .intro:hover {
            color: red;
          }
    
        `,
          <p className="intro">CSS-in-JS made simple -- just Style It.</p>
        );
      }
    }
    
    export default Intro;
    

    JSX Syntax (JSFIDDLE)

    import React from 'react';
    import Style from 'style-it';
    
    class Intro extends React.Component {
      render() {
        return (
          <Style>
          {`
            .intro:hover {
              color: red;
            }
          `}
    
          <p className="intro">CSS-in-JS made simple -- just Style It.</p>
        </Style>
      }
    }
    
    export default Intro;
    
    0 讨论(0)
提交回复
热议问题