react 项目中引入图片的几种方式

几种react中插入图片以及背景图片的方式

  • img标签引入图片
    因为react其实是通过js的reader函数渲染的页面,所以直接写src=“路径”是无法引入图片
    需要用下面的方式引入
<img src={require('../images/picture.png')} alt="标签"/>
  • 背景图片引入
    1 第一种就是常规的 新建一个css文件,然后就可以直接写css语法了
.img {
   background: url('../images/picture.png') 0 0 no-repeat;
}

2 第二种就是在react组件中通过变量的方式引入,然后直接将变量赋值给img标签

// 引入图片文件
import bg from '../images/bg.png'
// 通过字符串拼接的方式定义一个样式对象
const imgStyle = {
  width: '100%',
  height: '500px',
  backgroundImage: 'url(' + bg + ')',
  backgroundPosition: 'center 0',
  backgroundSize: '2045px 472px',
  backgroundRepeat: 'no-repeat'
}
class Home extends Component {
	constructor () {
		super (props)
	}
	render() {
		// 最后直接将变量赋值给标签
		<div style="imgStyle">
			...
		</div>
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45289067/article/details/94852902
今日推荐