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

3

我正在使用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 墙壁!

我做错了什么?

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

1个回答

4

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

const controlsRef = useRef<OrbitControls>(null);

我不确定要使用哪种接口/输入法,因为我不熟悉你正在使用的库,但这是一般想法。
此外,在你的 useEffect 钩子中,如果你使用 TypeScript 3.7.5 及以上版本,则可以使用可选链操作符。
useFrame(() => controlsRef?.current?.update());

我必须为Library添加自己的类型,但我完全忽略了这一点。我将类型添加到useRef中,它可以工作!但是当我将null添加为默认值时,在controlsRef.current.target =上会出现错误...我又困惑了...如果我不放置null,那么它默认为null/undefined? - Olly
嗯...是的,如果您不放置null,它会是“未定义”的。您现在面临什么错误? - wentjun
所以,如果我将null添加为默认值,那么就会出现controlsRef.current.target = ...这一行的错误提示:"Object is possibly 'null'"。但是,如果我将默认值保留为undefined,则完全没有问题。 - Olly
1
嗯...如果我们将其保留为未定义,是否没有其他问题?在这种情况下,让我们将其保留为 undefined :) 无论如何,到最后都不应该有影响,因为 controlsRef 肯定会被赋值为来自 OrbitControls 的 ref。 - wentjun
1
是的,基本上我的想法也是这样。因为它是一个useRef,我不认为它会引起任何问题。谢谢! - Olly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接