首页 > 解决方案 > React,每个数组元素的 z-index

问题描述

不久前,我在这里收到了答案,如何将每个 img 增加为数组的成员。不知何故,相同的原则不适用于 z-index(增加的 img 应该位于其余部分之上),尽管控制台显示 z-index 已更改。为什么? 在此处输入图像描述

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>                  
); 
}
}

https://jsfiddle.net/Nata_Hamster/fbs3m4jL/

标签: cssreactjsstatez-index

解决方案


添加position: 'relative',到返回的对象,getImgStyle因为z-index仅在postion设置为static(其默认值)以外的其他值时才有效。最简单的方法是使用relative,因为元素仍然是文档流的一部分。

https://jsfiddle.net/fbs3m4jL/7/


推荐阅读