代码之家  ›  专栏  ›  技术社区  ›  David Lin

使用useRef钩子的React Fiber Mesh元素,“ref.current”可能是“未定义的”

  •  0
  • David Lin  · 技术社区  · 1 年前

    环境
    Next JS,TypeScript,React Fiber

    代码段

    import { useFrame } from '@react-three/fiber'
    import React, { useRef, useState } from 'react'
    
    interface PolyhedronCanvasProps {
        position: [number, number, number],
        polyhedron: any
    }
    
    const PolyhedronCanvas = ( props: PolyhedronCanvasProps ) => {
        const ref = useRef()     
        const [count, setCount] = useState(0)
    
        useFrame((_, delta) => {  
            ref.current.rotation.x += delta
            ref.current.rotation.y += 0.5 * delta
        })
    
        return (
            <mesh 
                position={props.position}
                ref={ref}            
                onPointerDown={() => setCount((count + 1) % 3)}
                geometry={props.polyhedron[count]}
            >
                <meshPhongMaterial color={'lime'} wireframe/>
            </mesh>
        )
    }
    
    export default PolyhedronCanvas    
    
    ref.current.rotation.x += delta
    ref.current.rotation.y += 0.5 * delta
    

    我可能可以运行下一个js应用程序,但在这两行中仍然出现TypeScript错误 'ref.current' is possibly 'undefined'

    同样,我可以运行该项目,但我想删除TypeScript错误,这会使我的jsx文件在VS代码中变红。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Ori Drori    1 年前

    设置的类型 ref (请参阅 docs ):

    import { Mesh } from 'three'
    
    const ref = useRef<Mesh>(null)     
    

    检查是否 ref.current 在分配值之前已存在:

    useFrame((_, delta) => {  
      if(ref.current) {
        ref.current.rotation.x += delta
        ref.current.rotation.y += 0.5 * delta
      }
    })