Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

reactjs - How to pass an image as a prop in Typescript

I have just started to use Typescript and got an issue, possibly a basic.

I am trying to pass some images as props by using following code. And, I am getting the result of attached image. But, it does not display the images, which are passed as props.

I assume the relevant type for images, that I have used is wrong, but I could not find a way to rectify that error. I was just trying by replacing some types for the images, as per my understanding.

interface Props {
  thumbnailHeading: string;
  playBtn: string | undefined;
  thumbnail: string | undefined;
}

export const DisplayBox = memo(
  (props: Props): JSX.Element => {
    return (
      <div className="grid-container">
        <div className="box">
          <img className="samllImage" src={props.playBtn} />
          <img className="largeImage" src={props.thumbnail} />
          <div className="content">{props.thumbnailHeading}</div>
        </div>
      </div>
    );
  },
);

This is how I assigned related props, defined by above code.

<DisplayBox
   thumbnailHeading="Sample Text Title"
   playBtn="./image_files/SmallImage.png"
   thumbnail="./image_files/LargeImage.jpeg"
/>

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not an issue with TypeScript but they way you're importing or referring to the static image asset. When you're trying to include or import images or static assets, instead of directly sending the path, what you need to do is, import them first:

import SmallImage from "./image_files/SmallImage.png";
import LargeImage from "./image_files/LargeImage.jpeg";

And then you pass on the variables:

<DisplayBox
   thumbnailHeading="Sample Text Title"
   playBtn={SmallImage}
   thumbnail={LargeImage}
/>

This is because the code is compiled and assets are compressed by WebPack or whichever bundler that you're using. Also, make sure to do the same approach for any static assets that you're importing inside the src directory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...