React Three Fiber+TypeScript报错:Property 'rotation'不存在于never类型
React Three Fiber + TypeScript 错误修复:Property 'rotation' does not exist on type 'never'
你的代码有三个关键问题导致了这个TypeScript错误,直接按下面的步骤修复:
1. 给useRef指定正确类型
TypeScript不知道meshRef指向的是什么对象,默认把current推断为never。需要从three包导入Mesh类型,明确指定useRef的类型:import { Mesh } from 'three'; // ... const meshRef = useRef<Mesh>(null);2. 修正函数组件的语法
你的AnimatedBox组件写法有误,正确的函数组件定义应该是:const AnimatedBox = () => { // ... 组件逻辑 }或者用
function声明:function AnimatedBox() { // ... 组件逻辑 }3. 修正rotation的更新方式
Three.js里的rotation是一个Euler对象,不能直接用+=赋值数字,要针对具体的轴(x/y/z)更新:meshRef.current.rotation.x += 0.01; // 或者 y、z轴,根据需求选
修复后的完整代码
import React, { useRef } from "react"; import { Canvas, useFrame } from "@react-three/fiber"; import { Mesh } from "three"; const AnimatedBox = () => { const meshRef = useRef<Mesh>(null); useFrame(() => { console.log("hi"); if (meshRef.current) { meshRef.current.rotation.x += 0.01; } }); return ( <mesh ref={meshRef} scale={[0.5, 0.5, 0.5]}> <boxGeometry /> <meshStandardMaterial /> </mesh> ); }; export default function App() { return ( <div className="App"> <Canvas> <AnimatedBox /> <ambientLight intensity={0.1} /> <directionalLight /> </Canvas> </div> ); }
内容的提问来源于stack exchange,提问作者Virendra Pratap
相关产品推荐
相关产品推荐

