You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@react-three/xr v5+版本useHitTest语法转换及TS useRef问题咨询

适配@react-three/xr v5+版本的useHitTest及TypeScript Ref问题解决方案

a. ARCanvas弃用后添加hit-test特性

v5+版本移除了ARCanvas,改用<XR>组件包裹<Canvas>来配置AR会话。直接将sessionInit传递给<XR>组件的props即可:

import { Canvas } from '@react-three/fiber';
import { XR } from '@react-three/xr';

export default function App() {
  return (
    <Canvas camera={{ position: [0, 1.6, 0] }}>
      <XR sessionInit={{ requiredFeatures: ['hit-test'] }}>
        {/* 放置你的AR交互组件 */}
      </XR>
    </Canvas>
  );
}

b. 是否仍需要hit.decompose

不需要。v5+的useHitTest Hook会直接返回包含position、rotation、matrix的对象,这些属性已经是分解后的结果,无需手动调用decompose方法。

c. 矩阵操作与ref写法的变化

不需要手动调用mesh.applyMatrix4(hitMatrix),也无需依赖ref绑定位置。直接将useHitTest返回的position和rotation绑定到mesh的对应属性即可:

import { useHitTest } from '@react-three/xr';

export function HitIndicator() {
  const hit = useHitTest();
  if (!hit) return null;

  return (
    <mesh position={hit.position} rotation={hit.rotation}>
      <sphereGeometry args={[0.05]} />
      <meshBasicMaterial color="hotpink" />
    </mesh>
  );
}

如果需要直接操作矩阵,也可以使用hit.matrix属性,但日常场景用position/rotation更直观。

d. TypeScript中Ref类型不匹配的解决

出现Type 'MutableRefObject<undefined>' is not assignable错误,是因为没有给ref指定正确的类型。解决方式有两种:

  1. 明确指定ref类型并初始化为null:
import { useRef } from 'react';
import { Mesh } from 'three';

export function MyInteractiveMesh() {
  const meshRef = useRef<Mesh>(null);

  // 使用ref前先检查是否存在
  const handleClick = () => {
    if (meshRef.current) {
      meshRef.current.material.color.set('blue');
    }
  };

  return (
    <mesh ref={meshRef} onClick={handleClick}>
      <boxGeometry args={[0.2, 0.2, 0.2]} />
      <meshStandardMaterial />
    </mesh>
  );
}
  1. 允许ref为undefined(按需使用):
    如果组件逻辑需要ref初始为undefined,可以显式声明联合类型:
const meshRef = useRef<Mesh | undefined>(undefined);

注意使用时必须先判断ref是否存在,避免空值访问错误。

内容的提问来源于stack exchange,提问作者timhc22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:50:19