走马灯功能需求:
- 支持定时切换;
- 支持左右按钮切换(根据鼠标是否在切换组件内展示和隐藏左右切换按钮);
- 支持底部标识切换;
走马灯 完整代码如下:
/*** @class 走马灯*/import react, { Component } from 'react';
import './index.less';
import React from 'react';export default class CarouselCpn extends Component {/*** @param {*} props.itemList 传入元素数组 []* @param {*} props.autoplay 是否自动切换,默认false* @param {*} props.autoplaySpeed 自动切换的间隔(毫秒),默3000ms*/constructor(props) {super(props);const { itemList = [], autoplay = false, autoplaySpeed = 3000 } = props;this.timer = 0; //计时器this.state = {pointIndex: 0,autoplaySpeed, // 自动切换的间隔(毫秒)boxLen: 0, // 内容长度autoplay, // 是否自动切换itemList, // 传入元素数组 []};}onMounted() { }componentDidMount() {const { itemList } = this.state;this.setState({boxLen: itemList.length,})if (this.state.autoplay) {this.play();}}/*** 右按钮事件*/goRight() {if (this.state.pointIndex < (this.state.boxLen - 1)) {this.setState({pointIndex: this.state.pointIndex + 1,})} else {this.setState({pointIndex: 0,})}}/*** 左侧切换按钮*/onclickLeftBtn() {if (this.state.pointIndex == 0) {this.setState({pointIndex: (this.state.boxLen - 1),});} else {this.setState({pointIndex: this.state.pointIndex - 1,});}}/*** 右侧切换按钮*/onclickRightBtn() {if (this.state.pointIndex < (this.state.boxLen - 1)) {this.setState({pointIndex: this.state.pointIndex + 1,});} else {this.setState({pointIndex: 0,});}}/*** 点击对应的点* * @param {*} indexValue 序号标识*/onClickPoint(indexValue) {this.setState({pointIndex: indexValue,})}/*** 开始定时*/play() {this.timer = setInterval(() => {this.goRight();}, this.state.autoplaySpeed);}/*** 是否清除定时* @param {boolean} isRight * @returns */setTimer = (isRight) => {if (this.state.autoplay) {if (!isRight) {clearInterval(this.timer);this.timer = 0;} else if (isRight) {this.play();}}}render() {const { pointIndex, itemList } = this.state;const { keyIndex } = this.props;return (<divclassName="wrap"key={keyIndex}onMouseMove={this.setTimer.bind(this, false)}onMouseLeave={this.setTimer.bind(this, true)}style={{ width: '460px', height: '292px' }}><ul className="list" style={{ width: '460px', height: '292px' }}>{itemList.map((itemVaue, indexValue) => {return <liclassName={indexValue === pointIndex ? 'item active' : 'item'}key={`item${indexValue}`}style={{zIndex: indexValue === pointIndex ? 20 : 1,opacity: indexValue === pointIndex ? 1 : 0,}}>{itemVaue}</li>;})}</ul><ul className="pointList">{itemList.map((itemVaue, indexValue) => {return (<liclassName={indexValue === pointIndex ? 'point active' : 'point'}data-index={indexValue}onClick={this.onClickPoint.bind(this, indexValue)}key={`point${indexValue}`}></li>);})}</ul><button className="btn" id="leftBtn" onClick={this.onclickLeftBtn.bind(this)} style={{ display: 'none' }}>{'<'}</button><button className="btn" id="rightBtn" onClick={this.onclickRightBtn.bind(this)} style={{ display: 'none' }}>{'>'}</button></div>);}
}