如何在按下鼠标时重复调用函数?

时间:2019-04-13 18:10:02

标签: javascript reactjs onclick react-hooks

我正在使用react来构建需要使用我的网络摄像头的前端。我需要能够单击并按住一个按钮,然后反复调用一个将从相机抓取帧的函数。

import React,{useState,useRef,useEffect} from "react"


export function VideoFeed(){
const[constraints] = useState({width:300,height:300})
const longPress = useLongPress(takePhoto)

let video = useRef(null)

useEffect(()=>{
    navigator.mediaDevices.getUserMedia({video:true})
    .then(stream=>{
        let vid = video.current
        vid.srcObject = stream;
        vid.play();
    })
    .catch(e=>{
        console.log(e)
    })
},[video])

function takePhoto() {
        console.log("hey")
}

return(
    <div>
        <video autoPlay ={true} ref ={video} width={constraints.width} 
            height={constraints.height}>
        </video>
        <button {...longPress}>Snap Photo</button>
    </div>
    )
}


export function useLongPress(callback=()=>{}) {
 const [startLogPress, setStartLongPress] = useState(false);

   useEffect(() => {
   let timerId;
    if (startLogPress) {
      timerId = setTimeout(callback, 0);
    } else {
      clearTimeout(timerId);
    }

return () => {
  clearTimeout(timerId);
};
 }, [startLogPress]);

    return {
      onMouseDown: () => setStartLongPress(true),
      onMouseUp: () => setStartLongPress(false),
      onMouseLeave: () => setStartLongPress(false),
      onTouchStart: () => setStartLongPress(true),
      onTouchEnd: () => setStartLongPress(false),
   };
}

我使用钩子,无法弄清楚如何循环该函数。如果我在useEffect挂钩中添加了while循环,则应用程序将中断。单击可以工作,但单击并保持不起作用

2 个答案:

答案 0 :(得分:1)

这是一个使用setInterval函数的示例。希望它适合您的特定情况。

var value = 0;
var interval;

function update() {
  value++;
  document.getElementById("value-display").innerHTML = "Value: " + value;
}

function down() {
  value = 0;
  interval = setInterval(update, 100);
}

function up() {
  clearInterval(interval);
}
<h3 id="value-display">
  Value:
</h3>

<button type="button" onmousedown="down()" onmouseup="up()">
  Click me!
</button>

答案 1 :(得分:0)

您可以同时使用useIntervaluseState来决定是否触发功能。

function useInterval(callback, delay) {
  const savedCallback = useRef();

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

const onMouseDown = () => {
  console.log("mouse is down");
};

function App() {
  const [isMouseDown, setMouseDown] = useState(false);

  useInterval(onMouseDown, isMouseDown ? 100 : null);

  return (
    <div className="App">
      <h1
        onMouseDown={() => setMouseDown(true)}
        onMouseUp={() => setMouseDown(false)}
      >
        Mouse down here tp trigger the <i>onMouseDown</i> function
      </h1>
    </div>
  );
}

Run in CodeSandBox