onMouseEnter和onMouseLeave触发所有映射元素

时间:2017-07-23 17:30:20

标签: reactjs ecmascript-6

我试图对我的映射项目进行悬停效果,但鼠标事件会触发所有项目。

我怀疑我正在失去this或者我改变状态的方式是错误的,而且我正在为共享它的所有元素弄乱它。

这是一个剪辑:

  constructor(props) {
  super(props);
    this.state = {
      scale: 1,
      shadow: 0
    };
  }

  handleMouseEnter = () => {
    this.setState({
      scale: 1.1,
      shadow: 1,
    })
  }

  handleMouseLeave = () => {
    this.setState({
      scale: 1,
      shadow: 0
   })
 }

  render() {
    return (
      <div>
          {data.products.map((item, index) =>
            <Paper 
              key={index} 
              elevation={this.state.shadow} 
              style={{transform: `scale(${this.state.scale})`}}
              onMouseEnter={this.handleMouseEnter}
              onMouseLeave={this.handleMouseLeave}
            >
              {item.text}
            </Paper>
          )}
      </div>   
    );
  }

1 个答案:

答案 0 :(得分:1)

我有同样的问题。

我通过使用onMouseOver和onMouseOut而不是onMouseEnter和onMouseLeave进行修复,并在具有自己状态的新容器中写入处理程序。

这种情况适合您的情况:

第一部分:

constructor(props) {
    super(props);
    this.state = {

    };
}
render() {
    return (
        <div>
            {data.products.map((item, index) =>
                return <Paper key={index} />
            )}
        </div>
    );
}

第二部分

constructor(props) {
    super(props);
    this.state = {
        scale: 1,
        shadow: 0
    };
}

handleMouseEnter = () => {
    this.setState({
        scale: 1.1,
        shadow: 1,
    })
}

handleMouseLeave = () => {
    this.setState({
        scale: 1,
        shadow: 0
    })
}

render() {
    return (
        <div elevation={this.state.shadow} 
             onMouseOver={this.handleMouseEnter} 
             onMouseOut={this.handleMouseLeave} 
             style={transform: `scale(${this.state.scale})`}>
                {this.props.item.text}
        </div>
    );
}