如何在react three-fiber/three.js上创建点击事件监听器



我试图在react三纤维画布上侦听点击事件。但是当使用addEventListener时,我得到了一个不同的事件。

onClick网格属性返回以下事件:

<mesh position={[0, 0, 0]} onClick={(e) => console.log('onClick mesh: ', e)}>
<boxGeometry attach="geometry" args={[10, 10, 10]} />
<meshStandardMaterial attach="material" color="hotpink" wireframe />
</mesh>
onClick mesh:  
{dispatchConfig: Object, _targetInst: FiberNode, nativeEvent: MouseEvent, type: "click", target: Object…} 
// This is the event I need!!

添加一个事件监听器会返回以下事件:

const ThreeEventListener = () => {
const onClickDocument = (e) => {
console.log('onClick document listener: ', e)
}
useEffect(() => {
document.addEventListener('click', onClickDocument, false)
return () => document.removeEventListener('click', onClickDocument)
})
return null
}
onClick document listener:  
MouseEvent {isTrusted: true, screenX: 1508, screenY: 427, clientX: 348, clientY: 178…}
// This is a normal DOM event from React that I dont need

演示(点击框启动事件(

我假设您第一次得到的是一个SyntheticEvent实例,React将其用作本机事件的包装器,并结合了一些有用的React三个光纤字段-这是文档。文档说,在他们的事件实现中有一个本地浏览器事件和三个.js有用的数据(这就是你收到的(。

我建议在合成事件中从原生事件中取出你需要的东西:

event.nativeEvent 

这里有一个使用名为three.interaction:的外部库的封闭解决方案

import { Interaction } from 'three.interaction'
const ThreeEventListener = () => {
useEffect(() => {
// init three.interaction on mount
const interaction = new Interaction(gl, scene, camera);
}, [])
const onClickScene = (event) => {
console.log('onClick scene listener: ', e)
}
useEffect(() => {
// attach callbacks to clicks thanks to three.interaction
scene.on('click', onClickScene)
return () => scene.on('click', () => {})
})
return null
}

由three.interaction创建的事件看起来像:

onClick scene listener:  InteractionEvent {stopped: false, target: Scene, currentTarget: Scene, type: "click", data: InteractionData, …}

最新更新