react-three-fiber & drei useTexture hooks 错误

react-three-fiber & drei useTexture hooks error

错误:未捕获的 R3F 挂钩只能在 Canvas 组件内使用!

错误位置:const terrainTexture = useTexture(url);

错误代码:

import { OrbitControls, Sky, useTexture } from '@react-three/drei';
import { Canvas } from '@react-three/fiber';
...

function App() {
  
  const terrainTexture = useTexture('/Environments/Tile/Tile_2048.png');

  return (
    <Canvas>
...
      <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -2, 0]}>
        <planeBufferGeometry args={[100,100]}/>
        <meshStandardMaterial map={terrainTexture}/>
      </mesh>
...
    </Canvas>
  );
}

export default App;


此代码 'useTexture' 工作正常。上面的代码有什么区别?

import { useGLTF, useAnimations, useTexture } from '@react-three/drei'
...
export default function ModelAnim({ ...props }) {
...
  const bakedTexture = useTexture('/Characters/Textures/Character_Texture_1024.png')

  useEffect(() => {
...
  }, [])

  return (
    <group ref={group} {...props} dispose={null}>
...
      <skinnedMesh
        geometry={nodes.Character.geometry}
        material={materials.Mat_Character}
        skeleton={nodes.Character.skeleton}
      >
        <meshStandardMaterial map={bakedTexture} map-flipY={false}/>
      </skinnedMesh>
    </group>
  )
}

useGLTF.preload('/Character.gltf')

您只能在 Canvas 组件内使用 React Three Fiber 挂钩。创建一个使用钩子的新组件,然后在 Canvas 组件内渲染该新组件,如下所示:

function Scene() {
  const terrainTexture = useTexture('/Environments/Tile/Tile_2048.png');

  return (
    <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -2, 0]}>
      <planeBufferGeometry args={[100,100]}/>
      <meshStandardMaterial map={terrainTexture}/>
    </mesh>
  );
}

function App() {
  return (
    <Canvas>
      <React.Suspense fallback={<></>}>
        <Scene />
      </React.Suspense>
    </Canvas>
  );
}