走馬燈功能需求:
- 支持定時切換;
- 支持左右按鈕切換(根據鼠標是否在切換組件內展示和隱藏左右切換按鈕);
- 支持底部標識切換;
走馬燈 完整代碼如下:?
/*** @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>);}
}