React - 我们能否计算鼠标悬停在组件上的时间差?

时间:2021-08-12 04:00:47

标签: javascript reactjs

我正在尝试构建一个 React 组件,其中需要计算当鼠标悬停在 div 上时的 onMouseEnter 和 onMouseLeave 之间的时间差。我已将“time”添加到状态中,但不知道如何继续进行。由于我是 React 的新手,所以无法使其正常工作。请帮助我……此外,当我尝试显示这些元素时,我不确定要显示哪个时间戳属性。

import React from 'react';
import '../Hover/Hover.css';

class Hover extends React.Component {
    constructor(props) {
        super(props);
        this.handleMouseEnter = this.handleMouseEnter.bind(this);
        this.handleMouseLeave = this.handleMouseLeave.bind(this);
        this.state = {
            isHovering: false,
            time: 0
        }
    }

    handleMouseEnter(elementEnter){
        console.log("mouseenter : ", elementEnter.timeStamp)
        this.setState({
            isHovering: true
        })
    }

    handleMouseLeave(elementLeave) {
        console.log("mouseleave : ", elementLeave.timeStamp)
        this.setState({
            isHovering: false
        })
    }

    render() {
        return(
            <div className="hover" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
                <h1>Hover Component</h1>
            </div>

        )
    }
}

2 个答案:

答案 0 :(得分:5)

import React from 'react';
import '../Hover/Hover.css';

class Hover extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseEnter = this.handleMouseEnter.bind(this);
    this.handleMouseLeave = this.handleMouseLeave.bind(this);
    this.state = {
      isHovering: false,
      enterTime: 0,
      leavingTime: 0,
    }
  }

  handleMouseEnter(elementEnter){
    this.setState({
      isHovering: true, leavingTime: Date.now(),
    })
  }

  handleMouseLeave(elementLeave) {
    this.setState({
      isHovering: false, enterTime: Date.now(),
    })
  }

  render() {
    const hoverTime = this.state.leavingTime - this.state.enterTime;

    return(
      <div className="hover" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
        <h1>Hover 组件</h1>
        { hoverTime > 0 && '持续时间是:' + hoverTime }
      </div>
    )
  }
}

答案 1 :(得分:1)

你可以添加一个状态来存储时间 handleMouseEnter

constructor(props) {
    super(props);
    this.handleMouseEnter = this.handleMouseEnter.bind(this);
    this.handleMouseLeave = this.handleMouseLeave.bind(this);
    this.state = {
        isHovering: false,
        time: 0,
        start: 0
    }
}

handleMouseEnter(elementEnter){
    console.log("mouseenter : ", elementEnter.timeStamp)
    this.setState({
        isHovering: true,
        start: new Date()
    })
}

handleMouseLeave(elementLeave) {
    const newTime = new Date();
    this.setState({
        isHovering: false,
        time: Math.abs(new Date()-this.state.start) // 毫秒
        start: 0
    })
}