如何正确将 jsx 转换为 tsx

sim*_*ple 3 typescript reactjs gltf react-three-fiber react-three-drei

如何将退出的 jsx 文件从npx gltfjsx命令正确转换为TypeScript文件?无法纠正错误。

\n
import React, {useRef} from 'react'\nimport { useGLTF } from '@react-three/drei'\n\nexport default function Crown(state: any, { ...props }) {\n    const group = useRef()\n    // @ts-ignore\n    const { nodes, materials } = useGLTF('/crown.glb') //TS2339: Property 'materials' does not exist on type 'GLTF'.\n    return (\n        <group\n            // @ts-ignore\n            ref={group} //TS2322: Type 'MutableRefObject<undefined>' is not assignable to type 'Ref<Group> | undefined'. \xc2\xa0\xc2\xa0Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<Group>'. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Types of property 'current' are incompatible. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type 'undefined' is not assignable to type 'Group | null'.\n            {...props}\n            dispose={null}\n        >\n            <mesh..../>\n            <mesh..../>\n            <mesh..../>\n            <mesh..../>\n        </group>\n    )\n}\n\nuseGLTF.preload('/crown.glb')\n
Run Code Online (Sandbox Code Playgroud)\n

小智 5

gltfjsx模块有一个可用的类型标志,因此您不必手动执行此操作。

每当我想将 .glb 转换为 .tsx 时,我只需执行npx gltfjsx file.glb -tnpx gltfjsx file.glb --types

有时这会给 ref 带来错误,如果您不需要 ref 您可以删除它,如果您这样做,我的解决方法是定义 ref 类型:

 <group
      ref={group as Ref<THREE.Group>}
      {...props}
      dispose={null}
    >
...
</group>
Run Code Online (Sandbox Code Playgroud)