简体   繁体   中英

How do I pass images as props in React typescript react function component export?

I am trying to import and pass an image as a prop to my Skill component from my Skills.tsx file. The image path is the following:

public/images/skill-logos/html.png.

Here is what my Skills.tsx file looks like:

import React from 'react';
import Skill from './Skill';
import HtmlLogo from '../public/image/skill-logos/html.png';

function Skills({}: Props) {
  return (
    <div>
        <h3>Skills</h3>
        <h3>Hover over a skill for current proficiency</h3>
        <div>
            <Skill 
              imageSource={HtmlLogo} 
              proficiency="80"
            />
        </div>
    </div>
  );
};


export default Skills;

And this is what my Skill.tsx file looks like:

import React from 'react';

type Props = {
    imageSource: string;
    proficiency: string;
};

function Skill({ imageSource, proficiency }: Props) {
    return (
        <div>
            <img 
                src={imageSource}
                alt='' 
            />
            <div>
                <p>{proficiency}%</p>
            </div>
        </div>
    );
};

export default Skill;

So far, it does not render the image, but it does render the proficiency.

So far i've tried using require('image_path') to import the image, but it didn't work. If anyone knows which method works, I would highly appreaciate it.

When you want to use an image from public directory, you should not use import .

Instead, you should do this:

import React from 'react';
import Skill from './Skill';

const HtmlLogo = process.env.PUBLIC_URL + "/image/skill-logos/html.png";

function Skills({}: Props) {
  return (
    <div>
        <h3>Skills</h3>
        <h3>Hover over a skill for current proficiency</h3>
        <div>
            <Skill 
              imageSource={HtmlLogo} 
              proficiency="80"
            />
        </div>
    </div>
  );
};


export default Skills;

Read more here .

Just add the path directly to the prop value

<Skill 
  imageSource={"./images/skill-logos/html.png"} 
  proficiency="80"
 />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM