我目前面临着仅通过传递路径将图像加载到我的卡片组件中的问题:
我的卡片组件如下所示:
interface CardProps {
imageLink: string;
alt: string;
title: string;
text: string;
}
const Card: React.FC<CardProps> = (props) =>{
return(
<div className="card">
<img className="card-image" src={props.imageLink} alt={props.alt}></img>
<h2 className="card-title">{props.title}</h2>
<p className="card-text">{props.text}</p>
</div>
);
}
export default Card
所以我希望卡片组件显示我在 App.tsx 中使用它时传递的图像
import Header from "./Header.tsx";
import Footer from "./Footer.tsx";
import Card from "./Card.tsx";
import Button from "./Button.tsx";
function App() {
return(
<>
<Header/>
<Card imageLink="./assets/testLogo.png" alt="Test" title="Test" text="Test"/>
<Button/>
<Footer/>
</>
);
}
export default App
显然我不想导入将来要使用的每个文件。到目前为止一切正常,只是图像加载不正确
有些人使用“require”,但它不包含在 TypeScript 中
我找到了一个完美的解决方案:
function getImageURL(name: String) {
return new URL(`../assets/${name}`, import.meta.url).href
}
export {getImageURL};
import { getImageURL } from "./utils/image-util.ts";
function App() {
return(
<>
<Header/>
<Card imageLink={getImageURL("testLogo.png")} alt="Test Logo" title="Test Title" text="Test text"/>
<Button/>
<Footer/>
</>
);
}
export default App
信用转到tapaScript