[英]React, z-index for each array element
不久前,我收到了答案,如何增加每个img作为数组的成员。 尽管控制台显示z-index发生了变化,但z-index的相同原理不知所措(增加的img应该位于其余部分的顶部)。 为什么?
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',
zIndex: this.state.showIncreaced === id ? '10' : '0',
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>
);
}
}
将position: 'relative',
添加到getImgStyle
返回的对象,因为z-index
仅在postion
设置为static
(默认值)以外的其他值时才起作用。 最简单的方法是使用relative
因为元素仍然是文档流的一部分。
这是因为默认情况下图像元素的position
是static
的。
如果您将图像位置更新为“ position:absolute;
,则zIndex
值将按预期工作。 要注意的是,您需要使用左坐标定位图像,使它们彼此相邻放置。 这是说明概念的getImgStyle
的更新版本:
getImgStyle (id) {
return {
position:'absolute', // Set absolute position
left: `${(id-1) * 100}px`, // Calculate a left coordinate for image
width: '20vw',
marginRight: '0.5vw',
marginLeft: '0.5vw',
zIndex: this.state.showIncreaced === id ? '10' : '0',
transform: this.state.showIncreaced === id ? 'scale(1.5, 1.5)' : 'scale(1, 1)'
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.