React中file类型input的useRef正确TypeScript类型查询
为type="file"的input指定正确的TypeScript Ref类型
对于type为file的input元素,对应的DOM类型是HTMLInputElement,所以你可以把ref的类型指定为这个,替换掉any:
const upload = useRef<HTMLInputElement>(null);
为什么是HTMLInputElement?
所有input元素(不管type是什么)对应的DOM接口都是HTMLInputElement,它包含了files属性(类型为FileList | null),正好匹配你代码中访问的upload.current.files。
类型安全的代码优化
因为upload.current可能为null,files也可能为null,为了避免运行时错误和TypeScript警告,建议在imgUpload函数里增加非空判断:
const imgUpload = () => { // 先确认ref指向的元素存在,且有选中的文件 if (!upload.current || !upload.current.files || upload.current.files.length === 0) { return; } console.log(upload.current.files[0], upload.current.files[1]); setImgFile(prev => [...prev, URL.createObjectURL(upload.current.files[0])]); };
修改后的完整代码
import { useState, useRef } from 'react'; export default function ImgUpload() { const [imgFile, setImgFile] = useState<string[]>([]); // 替换any为HTMLInputElement const upload = useRef<HTMLInputElement>(null); const imgUpload = () => { // 增加非空判断,提升类型安全 if (!upload.current || !upload.current.files || upload.current.files.length === 0) { return; } console.log(upload.current.files[0], upload.current.files[1]); setImgFile(prev => [...prev, URL.createObjectURL(upload.current.files[0])]); }; return ( <> <h1>image upload</h1> <input type='file' ref={upload} multiple onChange={imgUpload} accept='image/*' style={{ zIndex: '2', marginBottom: '10px', cursor: 'pointer', }} /> <h2>이미지 저장소</h2> <div style={{ display: 'flex' }}> {imgFile?.map((img, idx) => ( <div key={idx} style={{ margin: '20px', border: '1px solid black' }}> <img style={{ width: '200px', height: '200px ' }} src={img} alt='img' /> </div> ))} </div> </> ); }
内容的提问来源于stack exchange,提问作者kimjuno97
相关产品推荐
相关产品推荐

