我有Action组件
booksToReturn
但是当我有几张图片时,
state = {
highlight: null
}
handleLeave = () => {
this.setState({
highlight: null
})
}
handleHover = (e) =>{
this.setState({
highlight: 'highlight'
})
}
<img onMouseEnter={this.handleHover} onMouseLeave={this.handleLeave} className={`${this.state.highlight}`} src="img" />
然后,当您将鼠标悬停在其中一个上时,每个人都将获得className'highlight', 但是我只想突出显示鼠标悬停在上面的图像。 谢谢您提前回答!
答案 0 :(得分:0)
您只需使用简单的CSS即可在图片上实现悬停效果。
就是这样:
img.anyClassName:hover {
//css stuff
}
是否足以满足您的使用需求?
答案 1 :(得分:0)
您可以使用高阶分量方法。
// HOC that holds state/handlers and passes to wrapped component
const handleHover = (Component) =>
class extends React.Component {
state = {
highlight: null
}
handleLeave = () =>
this.setState({
highlight: null
})
handleHover = (e) =>
this.setState({
highlight: 'highlight'
})
render() {
return (
<Component
handleHover={handleHover}
handleLeave={handleLeave}
highlight={this.state.highlight}
/>
);
}
}
// Component that is wrapped with HOC that renders an <img> with handlers and state
const Img = handleHover(({
handleHover,
handleLeave,
highlight,
src
}) => (
<img
onMouseEnter={handleHover}
onMouseLeave={handleLeave}
className={`${highlight}`}
src={src}
/>
))
// Use `IMG` in your component, each will maintain it's own highlight state
<Img src="1.jpg" />
<Img src="2.jpg" />