react实现轮循图片,轮播图,图片引入方式详解~

本文默认你已经对react的一些语法有了基本了解的前提下;

由于react的图片引用机制会对一些初学者造成某些掣肘,例如react中图片无法像js一样使用相对路径展示图片,你需要展示本地图片的话必选使用一下的几种方式:

// 引入图片
import scrollimg1 from './img/1.jpg'
const scrollimg1 = require( './img/1.jpg');

引入之后你可以直接展示

<img src={scrollimg1} alt="图片加载失败" />

也可以用作背景图片

<div style={{ background: `url(${scrollimg1})`}}></div>

如果你需要在state中存储图片信息的话,那必须是网络图片,如果你无法提供网络图片也能实现,只是无法用到工作中,这里会有无网络图片时的应对方式

this.state = {
	// 正确的
    imgarrar: [
        'http://xxx.jpg',
        'http://xxx.jpg'
    ]
	// 错误、无效的
	// imgarrar: [
	//     '../images/1.jpg',
	//     '../images/2.jpg'
	// ]
}

此时我相信你已经将你需要轮循的图片正确的引入了
引入图片后我们先用循环渲染到页面上,再加点样式使其重叠

// html

<div className='scroll'>
	<div className='scroll_box'>
		{this.state.imgarrar.map(item => {
			return (
				<img src={item} alt="" />
			)
		})}
	</div>
</div>

// css

.scroll{
    display: flex;
    justify-content: center;
    padding-top: 30px;
}
.scroll_box{
    width: 160px;
    height: 90px;
    position: relative;
}
.scroll_box img{
    width: 100%;
    height: 100%;
    position: absolute;
}

紧接着我们要让图片更替展示该怎么做,此时需要用到我们的定时器,我的想法是在每一次定时器触发时用变量接收当前数组的第一张图片信息,再将原数组中的第一张图片信息删除,然后以push的方式在原数组末尾插入这一条数据以此达到轮循,这一步需要在生命周期中完成

// js

componentDidMount() {
    let _this = this
    _this.setState({
        time: setInterval(() => {
            let str = _this.state.imgarrar[0];
            _this.state.imgarrar.splice(0,1)
            _this.state.imgarrar.push(str)
            _this.setState({
                imgarrar: _this.state.imgarrar
            })
        }, 2000)
    })
}

在离开页面时销毁定时器,以免造成无用的性能消耗

componentWillUnmount() {
    this.setState({
        time: null
    })
}

以上是有网络图片的实现方式,下面是本地图片的实现方式,只是js和html部分需要改变写法,css不变

// js

this.state = {
	imgarrar: [],//图片数组
	time: null,//定时器
	scrollimg: ""//当前展示图片
}
componentDidMount() {
	let _this = this
    _this.setState({
        imgarrar: [scrollimg1,scrollimg2,scrollimg3,scrollimg4],
        scrollimg: [scrollimg1]
    },res=>{
        _this.setState({
            time: setInterval(() => {
                let str = _this.state.imgarrar[0];
                _this.state.imgarrar.splice(0,1)
                _this.state.imgarrar.push(str)
                _this.setState({
                    scrollimg: _this.state.imgarrar[0]
                })
            }, 2000)
        })
    })
}

// html

<div className='scroll'>
	<div className='scroll_box'>
		<img src={this.state.scrollimg} alt="" />
	</div>
</div>

我已经在此基础完成React的轮播图组件封装,感兴趣的可以跳转查看,连接奉上:https://blog.csdn.net/liaorihua/article/details/123731400

如果帮到你的话请点赞收藏加关注!!!
以上只是实现逻辑,具体样式和辅助功能还需完善,不足之处还请不吝指教。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值