使用 ReactJS 实现一个简易的轮播图 (carousel) 组件。
Task 1:在相框中展示图片,左右按钮切换当前图片
实现思路;把图片横向排列成组(image row),放置在相框(frame)中,隐藏超出相框的部分。利用图片组左侧和相框左侧的距离(margin-left)改变当前展示在相框中的内容,点击左右按钮可以改变这个距离。
// How to make use of this component
{images.map(image => )}
// Carousel component
import React, { Component } from 'react';
export default class Carousel extends Component {
constructor(props) {
super(props);
this.state = { currentIndex: 0 };
this.renderChildren = this.renderChildren.bind(this);
this.setIndex = this.setIndex.bind(this);
}
renderChildren() {
const { children, width, height } = this.props;
const childStyle = {
width: width,
height: height
};
return React.Children.map(children, child => {
const childClone = React.cloneElement(child, { style: childStyle });
return (
style={ {
display: 'inline-block'
}}
>
{childClone}
);
});
}
setIndex(index) {
const len = this.props.children.length;
const nextIndex = (index + len) % len;
this.setState({ currentIndex: nextIndex });
}
render() {
const { width, height } = this.props;
const { currentIndex } = this.state;
const offset = -currentIndex * width;
const frameStyle = {<