I have an element in my react app that has mouse events. However, it does not work on mobile because all the mouse event converts to touch events. I would do something like this
<div onMouseMove={mousemove}
onMouseUp={mouseup}
onMouseDown={mousedown}
onTouchMove={touchmove}
onTouchEnd={touchend}
onTouchStart={touchstart}>some content</div>
The problem here is that I didn't want to write so many JSX attributes. So I thought about this
const elementRef = useRef()
useEffect(()=>{
elementRef.addeventlistener('mousedown', mousedown)
{/* add the rest of the event listeners */}
})
<div ref={elementRef}></div>
But that is still a lot of code, so I though about this instead.
const eventhandler = e =>{
switch(e.type){
case 'mousedown':
mousedown();
break;
{/*add the rest*/}
}
}
Then somehow assign eventhandler
to my div
. Is there a way of doing that (not just React but vanilla javascript)?
You can move the desired props to the object, and then spread it on the component. Eg.
const getMouseEvents = (mousemove, mouseup, mousedown, touchmove) => ({
onMouseMove: mousemove,
onMouseUp: mouseup,
onMouseDown: mousedown,
onTouchMove: touchmove
[...]
});
<div {...getMouseEvents(mousemove, mouseup, mousedown, touchmove)}>
some content
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.