我正在使用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'
遗憾的是,一切都徒劳无功。我感觉自己在撞击一堵不可移动的 TypeScript 墙壁!
我做错了什么?
(如果需要,可以创建一个代码沙箱)
controlsRef.current.target =
上会出现错误...我又困惑了...如果我不放置null,那么它默认为null/undefined? - OllycontrolsRef.current.target = ...
这一行的错误提示:"Object is possibly 'null'"。但是,如果我将默认值保留为undefined,则完全没有问题。 - Ollyundefined
:) 无论如何,到最后都不应该有影响,因为controlsRef
肯定会被赋值为来自OrbitControls
的 ref。 - wentjun