react中使用资源(图片、视频)的几种方法

tech2025-12-15  19

在create-react-app搭建的react项目中

一、插入图片

1、jsx中直接写
<img src={require('../../../static/login/bg.jpg')} style={{width:"50px",height:"50px"}} alt=""/>
2、import导入
import bg from '../../../static/login/bg.jpg' <img src={bg} style={{width:"50px",height:"50px"}} alt=""/>

二、背景图片

1、行内样式
<div style={{width:"100%",height:"100%",backgroundImage:`url(${require('./bg.jpg')})`,backgroundSize:"cover"}}></div>
2、外部声明
<div style={styleList.wrap}></div> const styleList = { wrap: { display: "flex", width: "100%", height: "100%", backgroundImage: `url(${require('./bg.jpg')})`, backgroundSize:"cover" }, }
3、使用.css文件
<div className="wrap"></div> .wrap{ height: 100%; width: 100%; background: url('../../static/login/bg.jpg'); background-size: cover; display: flex; }

三、视频资源

引入视频资源时,跟图片一样,必须要写成 require形式,否则无效

四、原因

暂未总结!!!(自己摸索比较慢,写博客主要是记录学习中遇到的问题和解决方法,具体深入原因待后续了解清楚了会持续更新)

注:参考这篇博客

https://blog.csdn.net/zyx1303031629/article/details/80536969

//方式一:import tsIcon from '../images/typescript.jpeg'; //方式二:const tsIcon = require('../images/typescript.jpeg'); //使用方式一:<img src={tsIcon} alt="" /> //使用方式二:<div style={{background: `url(${tsIcon}) no-repeat`}}></div> //使用方式三:const styles = { test: { background: `url(${tsIcon}) no-repeat center` }}render() { return ( <div style={styles.test}></div> )}
最新回复(0)