threejs中group下绑定唯一key导致parten丢失的问题

技术架构

  • react
  • threejs
  • @react-three/drei
  • @react-three/fiber
  • @use-gesture/react

场景

一个分组下有一个Line,当使用gesture的useDrag触发事件以后:

import { Line } from '@react-three/drei'
import { ThreeEvent, useFrame } from '@react-three/fiber'
import { useDrag } from '@use-gesture/react'
import { useEffect, useState } from 'react'
import { DoubleSide, Vector3 } from 'three'

const lineWidth = 4
const LinePropsData = {
  color: 0x3b61fa,
  lineWidth: lineWidth,
  dashSize: lineWidth,
  gapSize: lineWidth,
  side: DoubleSide,
}

/**
 * 区域入参定义
 */
export interface ExampleProps {
  positions?: Vector3[]
}

const Example: React.FC<ExampleProps> = (props) => {
  const { positions = [] } = props
  const [linePositions, setLinePositions] = useState<Vector3[]>([...positions])
  useEffect(() => {
    if (!positions) {
      return
    }

    setLinePositions([...positions])
  }, [positions])

  const dragStateRef = useRef<GestureDragState>()
  const bind = useDrag((state) => {
    setDragState(state)
  })
  const bindObject = bind() as any

  // 每一帧更新 mesh 的位置
  useFrame(() => {
    const dragState = dragStateRef.current
    if (!dragState) {
      return
    }
    const event: ThreeEvent<MouseEvent> = dragState.event as any
    console.log('event.intersection.parent, event.intersections[0]?.object.parent)
  })

  return (
    <group {...bindObject}>
      {linePositions.length < 2 ? (
        // 两个以下的点构不成线
        <></>
      ) : (
        <Line key={Math.random()} points={linePositions} {...LinePropsData} />
      )}
    </group>
  )
}

export default Example

useFrame中获取相交对象的父级event.intersections[0]?.object.parent,发现父级为null,而Line明明在group下,父级应该为group才对。一时间百思不得其解,重新写了个Line发现父级能找到group,对比之下,发现旧的写法里绑定了个key={Math.random()}(暂时使用random代替源代码中的uuid生成),每次触发react重新渲染时都是渲染不同的元素,这导致了Line与group丢失了父子关系。

这是个有意思的问题,值得分享。

相关推荐

  1. threejsgroup唯一key导致parten丢失问题

    2024-01-09 05:50:01       36 阅读
  2. vuekey

    2024-01-09 05:50:01       19 阅读
  3. vue

    2024-01-09 05:50:01       14 阅读
  4. VueClass和style方式

    2024-01-09 05:50:01       20 阅读
  5. 3种事件异同(js问题

    2024-01-09 05:50:01       40 阅读
  6. wpf 模板内TemplateBinding失效问题

    2024-01-09 05:50:01       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-09 05:50:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-09 05:50:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-09 05:50:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-09 05:50:01       20 阅读

热门阅读

  1. 【TypeScript】声明文件

    2024-01-09 05:50:01       39 阅读
  2. SVG图标配置 Cannot find package ‘fast-glob’

    2024-01-09 05:50:01       38 阅读
  3. LLM_InterLM-Demo学习

    2024-01-09 05:50:01       47 阅读
  4. Golang学习之路一六运算符

    2024-01-09 05:50:01       37 阅读
  5. golang利用alpn机制实现优先以http2协议访问服务端

    2024-01-09 05:50:01       37 阅读
  6. 前端面试--moka

    2024-01-09 05:50:01       47 阅读
  7. spring之AOP源码分析上

    2024-01-09 05:50:01       43 阅读