如何仅通过传递路径来在 TypeScript 和 React 中的组件中使用图像?

问题描述 投票:0回答:1

我目前面临着仅通过传递路径将图像加载到我的卡片组件中的问题:

我的卡片组件如下所示:

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 中

reactjs typescript image dynamic
1个回答
0
投票

我找到了一个完美的解决方案:

  1. 在项目文件夹中创建一个“utils”文件夹
  2. 如果您使用 JavaScript,请创建“image-utils.ts”或 js。
  3. 编码如下:
function getImageURL(name: String) {
    return new URL(`../assets/${name}`, import.meta.url).href
}
export {getImageURL};
  1. 然后在您的应用程序中导入它,并在传递文件名时调用它
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
  1. 就是这样!没有要求,没有 webpack :)

信用转到tapaScript

© www.soinside.com 2019 - 2024. All rights reserved.