gpt4 book ai didi

reactjs - TS2532 - 对象可能未定义 - useRef 和 react-three-fiber

转载 作者:行者123 更新时间:2023-12-05 02:54:45 24 4
gpt4 key购买 nike

我正在实现一个带有 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 墙上!

我做错了什么?

(如果需要可以创建代码沙箱)

最佳答案

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

const controlsRef = useRef<OrbitControls>(null);

我不确定要使用的确切界面/类型,因为我不熟悉您正在使用的库,但这是总体思路。

此外,在您的 useEffect Hook 中,使用可选链接就足够了(前提是您使用的是 TypeScript 3.7.5 及更高版本)

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

关于reactjs - TS2532 - 对象可能未定义 - useRef 和 react-three-fiber,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61665175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com