class Article extends React.Component{
constructor(props) {
super(props)
this.state = {showIncreaced: false}
}
increase = () => {
this.setState({showIncreaced: !this.state.showIncreaced})
}
render(){
const TipStyle={
marginBottom: '10px'
}
const ImgStyle={
width: '20vw',
marginRight: '0.5vw',
marginLeft: '0.5vw',
transform: this.state.showIncreaced ? 'scale(1.5, 1.5)' : 'scale(1, 1)'
}
return(
<div style={TipStyle}>
<h2 style={{marginBottom: '1px'}}>{this.props.name}</h2>
<div>
<img style={ImgStyle} src={this.props.img1} onMouseOver={this.increase} onMouseOut={this.increase}/>
<img style={ImgStyle} src={this.props.img2} onMouseOver={this.increase} onMouseOut={this.increase}/>
<img style={ImgStyle} src={this.props.img3} onMouseOver={this.increase} onMouseOut={this.increase}/>
</div>
</div>
);
}
}
将鼠标悬停在图片上(例如img1)时,只应增加img1。但是所有带有style = {ImgStyle}的img都会增加。怎么了?
如果你想在悬停时只使其中一个增加,你需要使用id。我使用id而不是boolean更改了一些示例,并使用了其他改进网络:
class Article extends React.Component{
constructor(props) {
super(props)
this.state = {showIncreaced: null}
this.getImgStyle = this.getImgStyle.bind(this);
this.increase = this.increase.bind(this);
}
increase (incId) {
this.setState({showIncreaced: incId})
}
getImgStyle (id) {
return {
width: '20vw',
marginRight: '0.5vw',
marginLeft: '0.5vw',
transform: this.state.showIncreaced === id ? 'scale(1.5, 1.5)' : 'scale(1, 1)'
};
}
render(){
const TipStyle={
marginBottom: '10px'
}
return(
<div style={TipStyle}>
<h2 style={{marginBottom: '1px'}}>{this.props.name}</h2>
<div>
{[1,2,3].map((id) => {
return <img style={this.getImgStyle(id)} src={this.props[`img${id}`]} onMouseOver={this.increase.bind(this, id)} onMouseOut={this.increase} />
})}
</div>
</div>
);
}
}
您正在为每个图像切换增加的状态变量,然后将其应用于样式中的所有图像。您需要一种方法来区分图像上的悬停事件,以便您可以正确应用样式。
因此,您应该具有默认图像样式,然后使用具有已修改属性的另一种图像样式,并且仅将其应用于单个图像。