React-三纤维挂钩只能在 Canvas 组件内使用

Saq*_*qon 7 typescript reactjs react-three-fiber

我有这两个组件:

相机.tsx

import { useGLTF } from "@react-three/drei"


export default function Camera() {
  const gltf = useGLTF('/scene.gltf', true)
  return (
    <primitive object={gltf.scene} dispose={null}/>
  )
}
Run Code Online (Sandbox Code Playgroud)

并在 Landing.tsx 中使用它

import { Suspense, useRef } from 'react';
import { Canvas, useFrame } from 'react-three-fiber';
import { Html } from '@react-three/drei';
import Camera from '../components/Camera';
import Lights from '../components/Lights';

export default function Landing() {
    const mesh = useRef();
     useFrame(() => {
    (mesh.current as any).rotation.x  += 0.01
  })
    return (
        <div className='Landing'>
            <Canvas colorManagement camera={{ position: [0, 0, 250], fov: 70 }}>
                <Suspense fallback={null}>
                <Lights />
                    <mesh ref={mesh} position={[-6, 75, 0]}>
                        <Camera />
                    </mesh>
                    <Html fullscreen>
                        <div className='Landing-container'>
                            <h1 className='Landing-header'>WELCOME</h1>
                        </div>
                    </Html>
                </Suspense>
            </Canvas>
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

一切工作正常,图像加载......直到我使用钩子useFrame- 然后我得到一个错误 - React-三纤维钩子只能在 Canvas 组件中使用!我有点困惑,因为 ref 是Canvas组件的子组件

Cos*_*tar 22

useFrame需要Canvas上下文才能工作。您需要在作为 的后代放置的某个组件内调用 useFrame 挂钩Canvas。像这样的东西:

const MyMesh = () => {
  const refMesh = useRef();

  useFrame(() => {
    if(refMesh.current) {
      // rotating the object
      refMesh.current.rotation.x += 0.01;
    }
  });
  return (<mesh ref={refMesh} />);
}

export default () => (
  <Canvas>
    <MyMesh />
  </Canvas>

)
Run Code Online (Sandbox Code Playgroud)