2

我有这两个组件:

相机.tsx

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


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

并在 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>
    );
}

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

4

1 回答 1

6

useFrame需要Canvas上下文才能工作。您需要在作为Canvas. 像这样的东西:

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

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

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

)
于 2021-04-21T17:30:44.950 回答