0

我试图在我的反应三纤维画布上听点击事件。但是我在使用时遇到了不同的事件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

演示(单击框触发事件)

4

2 回答 2

0

我假设您第一次得到的是SyntheticEventReact用作​​原生事件的包装器的一个实例,并结合了一些对 react-three-fiber 字段有用的内容 - 这是doc。文档说在他们的事件实现中有一个本机浏览器事件和 three.js 有用的数据(这是你收到的)。

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

event.nativeEvent 
于 2021-03-21T11:52:06.103 回答
0

这是一个使用名为的外部库的封闭解决方案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, …}
于 2021-01-11T12:51:02.233 回答