React集成@react-three/xr出现编译类型错误,如何解决?
修复@react-three/xr编译错误:Property 'object3D' does not exist on type 'IntrinsicElements'
错误详情
编译时触发如下类型错误:
Failed to compile. ../../node_modules/@react-three/xr/src/DefaultXRControllers.tsx:8:65 Type error: Property 'object3D' does not exist on type 'IntrinsicElements'. 6 | import { XRController } from './XRController' 7 | > 8 | export interface RayProps extends Partial<JSX.IntrinsicElements['object3D']> { | ^ 9 | /** The XRController to attach the ray to */ 10 | target: XRController 11 | /** Whether to hide the ray on controller blur. Default is `false` */
项目代码
import { DefaultXRControllers, ARCanvas } from '@react-three/xr' <ARCanvas camera={{ position: [0, 0, -0.3] }}> <React.Suspense fallback={false}> <ambientLight /> <mesh position={[0, 0, 0]} scale={0.008}> <Model path={threeModelSrc} position={[0, -1.6, 0]} scale={0.75} /> </mesh> <pointLight position={[10, 10, 10]} /> <DefaultXRControllers /> </React.Suspense> </ARCanvas>
修复方案
1. 对齐依赖版本
该错误多因@react-three/xr与@react-three/fiber版本不兼容导致,执行以下命令更新到匹配的最新稳定版:
npm install @react-three/fiber@latest @react-three/xr@latest
2. 扩展TypeScript类型声明(仅TS项目)
若使用TypeScript,需手动为object3D补充JSX类型定义。在项目中创建类型声明文件(如src/types/three.d.ts),添加以下内容:
import * as THREE from 'three'; declare global { namespace JSX { interface IntrinsicElements { object3D: Partial<THREE.Object3D> & { children?: React.ReactNode }; } } }
同时确保tsconfig.json的include数组包含该类型文件路径:
{ "include": ["src/**/*", "src/types/**/*"] }
3. 清理缓存重新构建
缓存可能引发类型解析异常,清理后重新安装依赖并编译:
rm -rf node_modules package-lock.json npm install npm start
内容的提问来源于stack exchange,提问作者redlightfilms
相关产品推荐
相关产品推荐

