简体   繁体   中英

Why isn't the link color changing back to its previous color on mouse out in react?

I want to change the color of the link to grey, when the mouse hovers over it. It's working but when I leave the link with my mouse it doesn't change back to its previous color.

I already tried to change it back with the onMouseOut event, but this also doesn't work.

    handleOver(e){
        e.target.style.color = 'grey';
    }

    render() {
        const {classes} = this.props;
        return (
            <div>
                <Typography>
                    More information:
                    <Link href='http://localhost:3000' onMouseOver={this.handleOver} color='secondary'> User Manual </Link>
                </Typography>
            </div>
        )
    }

in this satiation you need to revert it back to its initial color onmouseleave as following:

   <Link
            href="http://localhost:3000"
            onMouseLeave={e => (e.target.style.color = "green")}
            onMouseOver={e => (e.target.style.color = "grey")}
            style={{ color: 'green' }}
          >

but it is not best practice to achieve this functionally it better to use css

using a:hover pseudo-class

onMouseOver means when the mouse moves over. It doesn't mean while the mouse is over.

So when the mouse moves over, you set the colour to grey.

You don't do anything when the mouse moves out.

You could write an onMouseOut handler that resets it ( ...color = "" ), but this would be better handled with a stylesheet and the :hover pseudo-class.

onMouseOut wont work because when you use color like this, it will be fixed to your objective in HTML There is 2 easy options:

  1. Make the onMouseOut change the color of your element to the color you want. element.style.color = 'your target color';
  2. Make the change of your color with another css property like: css:
.newColor{
    color: gray;
} 

javascript for mouse over:

handleOver(e){
        Element.classList.add = 'newColor';
    }

javascript for mouse out:

handleOut(e){
        Element.classList.remove = 'newColor';
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM