React TypeScript函数组件中如何传递图片作为Props?
问题:React组件传递public目录图片无法显示
我尝试从Skills.tsx导入public/images/skill-logos/html.png图片,作为Props传给Skill组件,但图片无法显示,熟练度能正常渲染。已试过require导入也无效,相关代码如下:
Skills.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;
Skill.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;
解决方法
1. 修正路径拼写错误
你导入时写的路径是../public/image/skill-logos/html.png,实际目标路径是public/images/skill-logos/html.png,少了一个s,先把路径修正为../public/images/skill-logos/html.png(注意根据Skills.tsx实际位置调整相对路径层级)。
2. 使用public目录资源的正确方式
放在public目录下的静态资源,无需通过import或require导入,直接使用根相对路径即可。因为构建工具会将public目录下的资源原封不动复制到产物根目录,直接写/images/skill-logos/html.png就能正确访问。
修改后的Skills.tsx代码:
import React from 'react'; import Skill from './Skill'; function Skills({}: Props) { return ( <div> <h3>Skills</h3> <h3>Hover over a skill for current proficiency</h3> <div> <Skill imageSource="/images/skill-logos/html.png" proficiency="80" /> </div> </div> ); }; export default Skills;
3. 若坚持使用import导入(可选)
如果你的项目构建工具支持导入public资源(如Create React App),确保导入路径完全正确,此时导入的变量会是编译后的图片URL,可直接用于img的src属性。例如:
// 假设Skills.tsx在src/components目录下,public在项目根目录 import HtmlLogo from '../../public/images/skill-logos/html.png';
内容的提问来源于stack exchange,提问作者Danyurioh
相关产品推荐
相关产品推荐

