React 轮播图的正确打开姿势

下面只关注 react 轮播图中的知识点,并不会去关注样式

实现

在 components 目录下创建 slideShow文件

import React, { Component, Children } from 'react'

export default class SildeShow extends Component {
    interval: any;
    state = {
        total: 0,
        current: 0
    }
    componentDidMount() {
        const { children } = this.props
        this.setState({
            total: Children.count(children)
        });
        //定时轮播
        this.interval = setInterval(this.showNext,1000)
    }
    componentWillUnmount() {
        clearInterval(this.interval)
    }
    showNext = () => {
        const {total,current}=this.state
        this.setState({
            current:current+1===total?0:current+1
        })
    }
    render() {
        const { children } = this.props;
        const bullets = Array(this.state.total).fill("o");
        bullets[this.state.current] = "•";
        return (
            <div className="slideshow">
                <div>{bullets}</div>
                {Children.toArray(children)[this.state.current]}
            </div>
        )
    }
}

使用

//...
     <SlideShow>
        <img src=""/>
        <img src=""/>
        <img src=""/>
     </SlideShow>
//...

总结

  • 主要使用到 Children API
    • Children.toArray
    • Children.count
  • 采用 props.children 获取组件之间内容

你可能感兴趣的:(React)