简体   繁体   English

'e.target.files' 可能是 'null'

[英]'e.target.files' is possibly 'null'

In my input component I extract file content after input.在我的输入组件中,我在输入后提取文件内容。 Took code from here 从这里获取代码

Error occurred on the line of onChange={e => handleFileChosen(e.target.files[0])} , to be more accurate, ts underlines e.target.files .错误发生在onChange={e => handleFileChosen(e.target.files[0])}行,更准确地说,ts 强调了e.target.files

Error message is 'e.target.files' is possibly 'null'错误消息是'e.target.files' is possibly 'null'

And here is the code:这是代码:

import styles from './Input.module.scss'
import { FileInputProps } from './FileInput.props';
import cn from 'classnames'
import { useState } from 'react';

export const FileInput = ({ ...props }: FileInputProps): JSX.Element => {
      const [fileContent, setFileContent] = useState<string>('')

      const handleFileChosen = (file: File) => {
            let fileReader = new FileReader()
            fileReader.onloadend = (e: Event) => {
                  const content = fileReader.result || ''
                  setFileContent(content.toString())
            }
            fileReader.readAsText(file)
      }

      return (
            <>
                  <input
                        type='file'
                        onChange={(e) => {handleFileChosen(e.target.files[0])}}
                  />
                  <p>{fileContent}</p>
            </>
      )
}

I've checked this SO page, but none of those solutions helped me我检查了这个SO 页面,但这些解决方案都没有帮助我

Please review this code请查看此代码

import React, {ChangeEvent, useEffect, useState} from 'react';

const FileUploadComponent = () => {
    const [base64Data, setBase64Data] = useState("");
    const [error, setError] = useState("");

    const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
        const files: FileList | null = e.target.files;
        const reader: FileReader = new FileReader();
        reader.onloadend = function () {
            setBase64Data(reader.result as string)
        }
        reader.onerror = function () {
            setError("Error file not reading");
        }
        reader.readAsDataURL(files?.[0] as File);
    }

    useEffect(()=> {
        console.log(base64Data)
    }, [base64Data])

    return (
        <div>
            <input
                className={"form-control"}
                type={"file"}
                onChange={handleFileChange}
            />
        </div>
    );
};

export default FileUploadComponent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM