javascript 在 JSX 中悬停时更改图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48703510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change image on hover in JSX
提问by new-boy-in-web-dev-business
How do I change an image on hoverin JSX
如何hover在 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')} />
回答by typekev
I will assume you are writing this code in a React component. Such as:
我假设您正在 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')}
/>
);
}
}
Targeting this.srcwill not work in this case as you are essentially looking for something named srcin your class. For instance this.srccould find something like this:
this.src在这种情况下,定位将不起作用,因为您实际上是在寻找src类中命名的东西。例如this.src可以找到这样的东西:
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 />上下文。您可以像这样轻松地做到这一点:
<img
onMouseOver={e => console.log(e)}
/>
From there you can target the currentTargetproperty, among others. This will enter the context of your element. So now you can do something like this:
从那里,您可以定位该currentTarget属性等。这将进入元素的上下文。所以现在你可以做这样的事情:
<img
src="img1"
onMouseOver={e => (e.currentTarget.src = "img2")}
/>
The same can be done for onMouseOut.
可以对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.
您可以在其他元素上使用相同的方法,因为您肯定需要再次执行此操作。但要小心,因为这不是唯一的解决方案。在较大的项目中,您可能需要考虑使用商店 ( Redux),并传递道具而不是改变元素。
回答by max li
Best is to manage this in the state:
最好是在状态下管理这个:
class App extends Component {
state = {
img: "https://i.vimeocdn.com/portrait/58832_300x300"
}
render() {
return (
<div style={styles}>
<img
src={this.state.img}
onMouseEnter={() => {
this.setState({
img: "http://www.toptipsclub.com/Images/page-img/keep-calm-and-prepare-for-a-test.png"
})
}}
onMouseOut={() => {
this.setState({
img: "https://i.vimeocdn.com/portrait/58832_300x300"
})
}}
/>
</div>
)
}
};

