我有以下組件正在作業,但我想通過正確輸入道具使其更加“打字稿”。如您所見,現在我將其設定為“任何”。這是我的代碼:
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
uj5u.com熱心網友回復:
您期望字串作為影像 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)是一個組件型別,需要正確傳遞 props。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479153.html
