我如何通过图像作为道具在React typescript React函数组件导出?



我试图导入和传递图像作为道具,我的技能组件从我的技能。tsx文件。镜像路径如下:

公共/图片/skill-logos/html.png。

以下是我的技能。TSX文件看起来像:
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;

这就是我的技能。TSX文件看起来像:

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;

到目前为止,它没有渲染图像,但它渲染了熟练程度。

到目前为止,我已经尝试使用require('image_path')导入图像,但它不起作用。如果有人知道哪种方法有效,我将非常感激。

当您想使用公共目录中的图像时,不应该使用import.

你应该这样做:

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;

点击这里阅读更多。

直接将路径添加到prop值

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

最新更新