React-three-fiber hooks只能在Canvas组件内使用
React-three-fiber hooks can only be used within the Canvas component
我有这两个组件:
Camera.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 can only be used within the Canvas 组件! 我有点困惑,因为 ref 是 Canvas
组件的子组件
useFrame
需要 Canvas
上下文才能工作。您需要在作为 Canvas
的后代放置的某些组件中调用 useFrame 挂钩。
像这样:
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>
)
我有这两个组件:
Camera.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 can only be used within the Canvas 组件! 我有点困惑,因为 ref 是 Canvas
组件的子组件
useFrame
需要 Canvas
上下文才能工作。您需要在作为 Canvas
的后代放置的某些组件中调用 useFrame 挂钩。
像这样:
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>
)