Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.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
Javascript FileReader.result不可分配给img';src&x27;_Javascript_Reactjs - Fatal编程技术网

Javascript FileReader.result不可分配给img';src&x27;

Javascript FileReader.result不可分配给img';src&x27;,javascript,reactjs,Javascript,Reactjs,我正在使用React.js和typescript在我的网站上构建图像上传程序 我正在尝试通过FileReader从输入读取文件,并使用FileReader.result设置名为“thumb”的反应状态 问题是状态thumb类型不能分配给 如何正确确定拇指状态 Type 'string | ArrayBuffer | null' is not assignable to type 'string | undefined'. Type 'null' is not assignable to ty

我正在使用React.js和typescript在我的网站上构建图像上传程序

我正在尝试通过
FileReader
从输入读取文件,并使用
FileReader.result
设置名为“thumb”的反应状态

问题是状态
thumb
类型不能分配给

如何正确确定拇指状态

Type 'string | ArrayBuffer | null' is not assignable to type 'string | undefined'.
  Type 'null' is not assignable to type 'string | undefined'.

另外,alt也对此表示不满

Type 'Blob' is not assignable to type 'string'.ts(2322)

import React,{FC,useRef,useState,useffect}来自“React”;
接口IImagerProps{
名称:字符串;
}
常量图像读取器:FC=()=>{
const[isLoading,setIsLoading]=useState(false);
const[thumb,setThumb]=useState(“”);
constfileref=useRef(新的Blob([],类型:{type:“image/png”}));
常量句柄=()=>{
const fileReader=new fileReader();
fileReader.onloadend=()=>{
设置加载(假);
setThumb(fileReader.result);
};
fileReader.readAsDataURL(fileRef.current);
};
useffect(()=>{
如果(fileRef!==名称){
HandlerReader();
}
}[拇指];
如果(孤岛加载){
返回…加载;
}

return;//您可以查看@JacobSmit我已经阅读了此引用,想在这里获得更合适的类型描述。这确实有帮助,我不明白您试图用fileRef或name变量实现什么。@JacobSmit感谢您的链接,但我已经在上面提到,这都是关于实现时的类型问题使用typescript。你给我的是完全的javascript文件,没有typescript。转换为typescript:你可以看看@JacobSmit。我已经读过这个参考,想在这里得到更合适的类型描述。有帮助吗,我不明白你试图用fileRef或name变量实现什么。@JacobSmit谢谢对于您的链接,我已经在上面提到过,这是关于使用typescript实现时的类型问题。您给我的完全是javascript文件,没有typescript。转换为typescript:
import React, { FC, useRef, useState, useEffect } from "react";

interface IImageReaderProps {
  name: string;
}
const ImageReader: FC<IImageReaderProps> = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [thumb, setThumb] = useState<string | ArrayBuffer | null>("");
  const fileRef = useRef<Blob>(new Blob([], { type: "image/png" }));
  const handleReader = () => {
    const fileReader = new FileReader();

    fileReader.onloadend = () => {
      setIsLoading(false);
      setThumb(fileReader.result);
    };

    fileReader.readAsDataURL(fileRef.current);
  };
  useEffect(() => {
    if (fileRef !== name) {
      handleReader();
    }
  }, [thumb]);

  if (isLoading) {
    return <p>...loading</p>;
  }

  return <img src={thumb} alt={fileRef.current} />; // <- this shows error 
};