new*_*ess 4 javascript onmouseover onmouseout jsx reactjs
如何hover在JSX中更改图像
我正在尝试这样的事情:
<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')} />
Run Code Online (Sandbox Code Playgroud)
小智 13
我假设你在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')}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
this.src在这种情况下,定位不起作用,因为您基本上在寻找src类中命名的内容.例如,this.src可以找到这样的东西:
src = () => (alert("a source"))
Run Code Online (Sandbox Code Playgroud)
但那不是你想要做的.您想要定位图像本身.
因此,您需要输入<img />上下文.你可以这样轻松地做到这一点:
<img
onMouseOver={e => console.log(e)}
/>
Run Code Online (Sandbox Code Playgroud)
从那里您可以瞄准该currentTarget物业等.这将进入元素的上下文.所以现在你可以这样做:
<img
src="img1"
onMouseOver={e => (e.currentTarget.src = "img2")}
/>
Run Code Online (Sandbox Code Playgroud)
同样可以做到onMouseOut.
您可以在其他元素上使用相同的方法,因为您肯定需要再次执行此操作.但要小心,因为这不是唯一的解决方案.在较大的项目中,您可能需要考虑使用商店(Redux),并传递道具而不是变异元素.
max*_* li 13
最好是在状态中管理这个:
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>
)
}
};
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/5437qm907l
Cat*_*na 5
另一种非类方法:
import arrow from "../images/arrow.svg";
import arrowHover from "../images/arrowHover.svg";
function Arrow() {
const [over, setOver] = useState(false);
return (
<div
onMouseOver={() => setOver(true)}
onMouseOut={() => setOver(false)}
>
<img
src={over ? arrowHover : arrow}
alt="arrow"
width="50"
height="50"
/>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9272 次 |
| 最近记录: |