Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 对象在严格模式下可能为空_Reactjs_Typescript - Fatal编程技术网

Reactjs 对象在严格模式下可能为空

Reactjs 对象在严格模式下可能为空,reactjs,typescript,Reactjs,Typescript,对于下面的事件处理程序,我正在获取的对象在typescript中可能为null,而不是我编写的任何其他事件处理程序函数 handleInputOnChange(事件)} /> const[file,setFile]=useState(); const[fileName,setFileName]=useState(“”); 常量handleInputOnChange=(事件:React.ChangeEvent)=>{ setFile(event.target.files[0]); setFile

对于下面的事件处理程序,我正在获取的对象在typescript中可能为null,而不是我编写的任何其他事件处理程序函数

handleInputOnChange(事件)}
/>
const[file,setFile]=useState();
const[fileName,setFileName]=useState(“”);
常量handleInputOnChange=(事件:React.ChangeEvent)=>{
setFile(event.target.files[0]);
setFileName(event.target.files[0]。名称为字符串);
};
如果我在tsconfig.json文件中关闭严格模式,错误就会消失


TS告诉您您的“文件”数组可能有空值。有两种处理方法:(1)处理null情况,例如编写代码,说明如果文件为null,则执行其他操作;(2) 如果您知道文件不能为空,您可以告诉TS使用非空断言运算符ie files![0]。

您的问题是访问
文件[0]。名称
:无法保证在该数组的第0个位置上有东西,您将尝试访问
。名称
未定义的
 const [file, setFile] = useState<File>();
 const [fileName, setFileName] = useState<string>('');

 const handleInputOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFile(event.target.files[0]);
    setFileName(event.target.files[0].name as string);
  };