简体   繁体   English

只要鼠标悬停在 React 中的元素上,就更改 state

[英]Change state as long as mouse is over an element in React

I have a counter functional component, with 2 buttons: increment and decrement and currently, when they're clicked , the state changes.我有一个计数器功能组件,有 2 个按钮: incrementdecrement ,当前,当它们被点击时,state 会发生变化。 But I want the state to change as long as the mouse is over the element .但我希望 state只要鼠标悬停在元素上就可以更改。 (not like onMouseOver that executes the event if the mouse is over, and then again when you move the mouse out from the element and then hover on the element again). (不像onMouseOver会在鼠标悬停时执行事件,然后当您将鼠标从元素中移出然后再次在元素上执行 hover 时再次执行该事件)。 I want it to be a constant hover event.我希望它是一个恒定的 hover 事件。

Heres my counter code:这是我的counter代码:

import React, { useState } from "react";
import "./styles.css";

export default function App() {

  const [counter, setCounter] = useState(0)

  return (
    <div className="App">
      <h1>{counter}</h1>
      <button onClick={() => setCounter(counter + 1)}>Increment</button>
      <button onClick={() => setCounter(counter - 1)} disabled={counter < 1 ? true : false}>Decrement</button>
    </div>
  );
}

I hope that makes sense.我希望这是有道理的。 Thanks in advance.提前致谢。

Here you go:这里是 go:

For that, you might need one state variable that start and stops the interval on mouse hover and out,为此,您可能需要一个 state 变量来启动和停止鼠标 hover 和 out 上的间隔,

Run the below code snippet, hope that will clear your doubts.运行下面的代码片段,希望能消除您的疑虑。

 const { useState, useEffect, useRef } = React; const App = () => { const _intervalRef = useRef(null); const [startCounter,setStartCounter] = useState(false); const [counter,setCounter] = useState(0); useEffect(() => { if(startCounter) { _intervalRef.current = setInterval(() => { setCounter((counter) => counter+1); },250); } else { clearInterval(_intervalRef.current); } return () => clearInterval(_intervalRef.current); },[startCounter]); return ( <div> <div onMouseOver={() => setStartCounter(true)} onMouseOut={() =>setStartCounter(false)}> HOVER ME TO START COUNTER: { counter } </div> </div> ); } ReactDOM.render(<App />, document.getElementById('react-root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react-root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM