TS2532-对象可能未定义-useRef和react三个光纤



我正在实现一个具有react three-fiber的组件,它看起来像这样:

const Controls = (props: any) => {
const controlsRef = useRef();
const { camera, gl } = useThree();
useFrame(() => controlsRef.current && controlsRef!.current!.update());
// ^ Errors with Object is possibly 'undefined'
useFrame(() => {
if (controlsRef !== undefined && controlsRef.current !== undefined) {
controlsRef.current.target = new THREE.Vector3(worldMap.length / 2 * CELL_WIDTH, 0, worldMap.length / 2 * CELL_WIDTH)
// ^ ALSO errors with Object is possibly undefined
}
})
return (
<orbitControls
{...props}
ref={controlsRef}
args={[camera, gl.domElement]}
enableRotate
enablePan={false}
maxDistance={100}
minDistance={5}
maxPolarAngle={Math.PI / 3}
/>
);
};

我试着添加:

if (controlsRef !== undefined && controlsRef.current !== undefined) {
controlsRef!.current!.target = ...
// Errors with target does not exist on type 'never'
}

以及:

useFrame(() => controlsRef.current && controlsRef?.current?.update());
// Errors with update does not exist on type 'never'

唉,没有用。我感觉我的头撞在了一堵无法移动的打字墙上!

我做错了什么?

(如果需要,可以创建代码沙盒(

您需要为useRef的遗传类型参数提供类型,并将其初始化为null。

const controlsRef = useRef<OrbitControls>(null);

我不确定要使用的确切接口/类型,因为我不熟悉您正在使用的库,但这是一般的想法。

此外,在您的useEffect挂钩中,使用可选链接(如果您使用TypeScript 3.7.5及以上版本,则提供(就足够了

useFrame(() => controlsRef?.current?.update());