React 18中如何通过props传递图片?求最佳实现方案
React 18中通过Props传递图片的正确方法
你当前直接传递字符串路径给Card组件的img props,打包工具(比如Webpack)无法将这个相对路径转换为构建后的正确资源路径,导致图片无法加载。以下是两种可行的解决方法:
方案1:父组件导入图片后传递(推荐)
这种方式更安全,打包工具会在编译时检查图片是否存在,避免运行时错误。
修改App.jsx
先在App组件中导入图片,再将导入的图片变量作为props传递给Card:
import Card from './components/Card' // 导入图片资源 import KatieZaferesImg from '../images/katie-zaferes.png' export default function App() { return ( <div className="container"> <Navbar /> <Hero /> <Card img={KatieZaferesImg} // 传递导入后的图片变量 rating="5.0" reviewCount={6} country="USA" title="Life lessons with Katie Zaferes" price={42} /> </div> ) }
修改Card.jsx
移除Card组件内的图片导入,直接使用props.img作为img标签的src值:
import "../css/index.css" import Star from '../images/star.png' function Card(props) { return ( <section className="experience-cards"> <div className="experience-item"> {/* 使用props传递的图片 */} <img className="card-image" src={props.img} alt="Olympic athlete Katie Zaferes"/> <p className="experience-text">Sold Out</p> </div> <div className="description-below"> <div className="rating"> <img className="star" src={Star} alt="Rating star" width={15}/> <p>{props.rating}</p><span>({props.reviewCount}) • {props.country}</span> </div> <p className="item-description">{props.title}</p> <p className="item-price"><span className="item-price">From ${props.price}</span> / person</p> </div> </section> ) } export default Card
方案2:直接传递路径字符串(不推荐)
如果不想在父组件导入图片,可以在Card组件中用require处理路径,但这种方式无法提前检查图片是否存在,容易出错:
App.jsx保持不变
<Card img="../images/katie-zaferes.png" // 其他props... />
修改Card.jsx的img标签
<img className="card-image" src={require(`${props.img}`)} alt="Olympic athlete Katie Zaferes"/>
内容的提问来源于stack exchange,提问作者Laura Pasqualone
相关产品推荐
相关产品推荐

