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

标签 reactjs typescript tslint react-three-fiber

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

相关文章:

html - Event.target.name 适用于输入但不适用于 div?

javascript - react : Grab change on input value done by jQuery

reactjs - 如何在我的 React 应用程序中触发 Bootstrap 弹出窗口

javascript - TypeScript - 如何防止使用构造函数中的变量覆盖类方法

typescript - 为什么 TSLint 和 JSLint 报告空 block ?

reactjs - 在 webpack 应用程序中引用 amd 模块(arcgis)

javascript - 点击 map 上的 angular2 openlayers 显示详细信息

angular - typescript 中有没有办法强制类实现/覆盖静态变量?

javascript - 使用 TypeScript react Children[] 问题

angular - 安装 angular2-notifications 后运行 lint 失败