在JSX中更改悬停图像

在JSX中更改悬停图像

本文介绍了在JSX中更改悬停图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JSX中的hover上更改图像

我正在尝试这样的事情:

<img src={require('../../../common/assets/network-inactive.png')}
onMouseOver={this.src = require('../../../common/assets/network.png')}
onMouseOut={this.src = require('../../../common/assets/network-inactive.png')} />
解决方案

我假设您正在React组件中编写此代码.如:

class Welcome extends React.Component {
  render() {
    return (
       <img src={require('../../../common/assets/network-inactive.png')}
       onMouseOver={this.src = require('../../../common/assets/network.png')}
       onMouseOut={this.src = require('../../../common/assets/network-inactive.png')}
       />
    );
  }
}

在这种情况下,

定位this.src无效,因为您实际上是在类中寻找名为src的东西.例如,this.src可以找到这样的东西:

src = () => (alert("a source"))

但这不是您想要做的.您要定位图像本身.

因此,您需要输入<img />上下文.您可以像这样轻松地做到这一点:

 <img
    onMouseOver={e => console.log(e)}
  />

从那里,您可以定位currentTarget属性,等等.这将输入您的元素的上下文.现在,您可以执行以下操作:

  <img
    src="img1"
    onMouseOver={e => (e.currentTarget.src = "img2")}
  />

对于onMouseOut也可以这样做.

您可以在其他元素上使用相同的方法,因为您肯定需要再次执行此操作.但是要小心,因为这不是唯一的解决方案.在较大的项目中,您可能需要考虑使用商店( Redux ),并传递道具而不是变异元素. /p>

How do I change an image on hover in JSX

I'm trying something like this:

<img src={require('../../../common/assets/network-inactive.png')}
onMouseOver={this.src = require('../../../common/assets/network.png')}
onMouseOut={this.src = require('../../../common/assets/network-inactive.png')} />
解决方案

I will assume you are writing this code in a React component. Such as:

class Welcome extends React.Component {
  render() {
    return (
       <img src={require('../../../common/assets/network-inactive.png')}
       onMouseOver={this.src = require('../../../common/assets/network.png')}
       onMouseOut={this.src = require('../../../common/assets/network-inactive.png')}
       />
    );
  }
}

Targeting this.src will not work in this case as you are essentially looking for something named src in your class. For instance this.src could find something like this:

src = () => (alert("a source"))

But that is not what you want to do. You want to target the image itself.

Therfore you need to enter the <img /> context. You can do that easily like this:

 <img
    onMouseOver={e => console.log(e)}
  />

From there you can target the currentTarget property, among others. This will enter the context of your element. So now you can do something like this:

  <img
    src="img1"
    onMouseOver={e => (e.currentTarget.src = "img2")}
  />

The same can be done for onMouseOut.

You can use this same method on your other elements, as you will certainly need to do this again. But be careful as this is a not the only solution. On bigger projects you may want to consider using a store (Redux), and passing props rather than mutating elements.

这篇关于在JSX中更改悬停图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 02:49