React 学习中,或许以后会有用
//Slider.jsx
import React from 'react';
import './Slider.scss';
export default class Slider extends React.Component {
constructor(props) {
super(props);
this.state = {
active : 0
};
this.itemCount = this.props.items.length;
}
componentDidMount() {
this.autoSlideStart();
}
componentWillUnmount() {
this.autoSlideEnd();
}
autoSlide() {
let {active} = this.state;
active = active + 1 < this.itemCount ? active + 1 : 0;
this.setState({
active : active
});
}
changeActiveItem(offset) {
let {active} = this.state;
let index = offset + active;
if (index < 0) {
index = this.itemCount - 1;
} else if (index > this.itemCount - 1) {
index = 0;
}
this.setState({
active : index
})
}
autoSlideStart() {
this.autoSlideTimer = setInterval(() =>
this.autoSlide(),
1000
);
this.setState({
isStopped : false
})
}
autoSlideEnd() {
clearInterval(this.autoSlideTimer);
this.setState({
isStopped : true
})
}
render() {
let {items} = this.props;
let {active, isStopped} = this.state;
return (
<div className="Slider"
onMouseEnter={this.autoSlideEnd.bind(this)}
onMouseLeave={this.autoSlideStart.bind(this)}>
<ul className="Items" style={{
width : this.itemCount * 100 + '%',
marginLeft : active * -100 + '%'
}}>
{items.map((item)=>
<li>{this.props.render(item)}</li>
)}
</ul>
<ul className="Dots">
{items.map((item, i)=>
<li className={i == active ? "active" : ""}
onClick={this.changeActiveItem.bind(this, i - active)}>
</li>
)}
</ul>
{isStopped &&
<div className="Control">
<div className="Prefix"
onClick={this.changeActiveItem.bind(this, -1)}>《</div>
<div className="Next"
onClick={this.changeActiveItem.bind(this, 1)}>》</div>
</div>
}
</div>
);
}
}
/*Slider.scss*/
.Slider {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
overflow: hidden;
height: 100px;
width: 400px;
ul {
display: flex;
flex-direction: row;
&.Items {
align-self: flex-start;
transition: margin-left .6s linear;
height: 100%;
li, li>* {
width: 100%;
height: 100%;
}
}
&.Dots {
position: absolute;
bottom: 20px;
right: 80px;
li {
border: 4px solid #666;
width: 16px;
height: 16px;
border-radius: 8px;
margin: 0 5px;
cursor: pointer;
&:hover {
background-color:#666;
border: 5px solid #CCC;
border-radius: 10px;
}
&.active {
background-color:#f6f;
border: 5px solid #f6f;
border-radius: 10px;
}
}
}
}
.Control {
display: flex;
justify-content: space-between;
position: absolute;
width: 100%;
bottom: 50%;
.Prefix, .Next {
font-size: 18pt;
color: #FFF;
cursor: pointer;
background-color: rgba(0, 0, 0,0.5);
&:hover {
background-color: rgba(0, 0, 0,0.7);
}
}
.Prefix {
padding-right: 15px;
}
.Next {
padding-left: 15px;
}
}
}
调用
<Slider items={data} render={(item)=>
<div>{item}</div>
}/>