props.src 的正确输入是什么? (打字稿)

What is the proper Typing for props.src? (Typescript)

我有以下组件在工作,但我想通过正确输入 props 使其更“Typescripty”。如您所见,现在我将其设置为“任何”。这是我的代码:

import React, {useState, useEffect} from "react";

type ImageSrc =  React.SetStateAction<null>

//The line in question here
const AsyncImage = (props: any) => {
  const [loadedSrc, setLoadedSrc] = useState<ImageSrc>(null);
  useEffect(() => {
      setLoadedSrc(null);
      if (props.src) {
          const handleLoad = () => {
              setLoadedSrc(props.src);
          };
          const image = new Image();
          image.addEventListener('load', handleLoad);
          image.src = props.src;
          return () => {
              image.removeEventListener('load', handleLoad);
          };
      }
  }, [props.src]);
  if (loadedSrc === props.src) {
      return (
          <img {...props} alt=""/>
      );
  }
  return null;
};

export default AsyncImage

您希望字符串作为图像 src 属性。即使它是另一种类型,使用打字稿它应该看起来像这样(只需在 TProps 类型中使用正确的类型):

import React, {useState, useEffect, FC} from "react";

type TProps = {
    src: string;
};

//The line in question here
const AsyncImage:FC<TProps> = (props) => {
    const [loadedSrc, setLoadedSrc] = useState<string>("");
    useEffect(() => {
        setLoadedSrc("");
        if (props.src) {
            const handleLoad = () => {
                setLoadedSrc(props.src);
            };
            const image = new Image();
            image.addEventListener('load', handleLoad);
            image.src = props.src;
            return () => {
                image.removeEventListener('load', handleLoad);
            };
        }
    }, [props.src]);
    if (loadedSrc === props.src) {
        return (
            <img {...props} alt=""/>
        );
    }
    return null;
};
export default AsyncImage;

此处React.FunctionComponent(或React.FC)是组件类型,需要正确传递道具。