Uploadthing报错:@uploadthing/react无FileWithPath导出成员
解决
Module '@uploadthing/react' has no exported member 'FileWithPath'错误 问题原因
Uploadthing版本迭代后,FileWithPath类型的导出位置发生变更,不再从@uploadthing/react模块导出,而是移至uploadthing/client模块。
解决方案
方案1:修正导入路径
将原导入语句:
import type { FileWithPath } from '@uploadthing/react'
替换为:
import type { FileWithPath } from 'uploadthing/client'
方案2:自定义兼容类型(可选)
如果不想依赖包内的类型,可以自行扩展File类型来兼容路径属性:
type FileWithPath = File & { path?: string }
直接在组件文件顶部定义该类型,无需导入。
修改后的完整代码示例
'use client' import type { FileWithPath } from 'uploadthing/client' import { useCallback, Dispatch, SetStateAction } from 'react' import { useDropzone } from '@uploadthing/react/hooks' import { generateClientDropzoneAccept } from 'uploadthing/client' import { Button } from '@/components/ui/button' import { convertFileToUrl } from '@/lib/utils' type FileUploaderProps = { onFieldChange: (url: string) => void imageUrl: string setFiles: Dispatch<SetStateAction<File[]>> } export function FileUploader({ imageUrl, onFieldChange, setFiles }: FileUploaderProps) { const onDrop = useCallback((acceptedFiles: FileWithPath[]) => { setFiles(acceptedFiles) onFieldChange(convertFileToUrl(acceptedFiles[0])) }, [onFieldChange, setFiles]) const { getRootProps, getInputProps } = useDropzone({ onDrop, accept: generateClientDropzoneAccept(['image/*']), }) return ( <div {...getRootProps()} className="flex-center bg-dark-3 flex h-72 cursor-pointer flex-col overflow-hidden rounded-xl bg-grey-50"> <input {...getInputProps()} className="cursor-pointer" /> {imageUrl ? ( <div className="flex h-full w-full flex-1 justify-center "> <img src={imageUrl} alt="image" width={250} height={250} className="w-full object-cover object-center" /> </div> ) : ( <div className="flex-center flex-col py-5 text-grey-500"> <img src="/assets/icons/upload.svg" width={77} height={77} alt="file upload" /> <h3 className="mb-2 mt-2">Drag photo here</h3> <p className="p-medium-12 mb-4">SVG, PNG, JPG</p> <Button type="button" className="rounded-full"> Select from computer </Button> </div> )} </div> ) }
额外提示:原代码中useCallback的依赖数组缺失onFieldChange和setFiles,会触发React Hooks依赖警告,已在示例中补充;另外accept的三元判断逻辑多余,直接调用generateClientDropzoneAccept(['image/*'])即可。
内容的提问来源于stack exchange,提问作者Amri Iqro
相关产品推荐
相关产品推荐

