如何为轮播中的幻灯片制作动画?

时间:2019-09-08 10:34:27

标签: css reactjs animation styled-components

我想创建一个轮播,但我不知道如何平滑幻灯片的动画。

如何?我试图用不透明性来做到这一点,但这是行不通的。

import React, { Component } from 'react'
import styled from 'styled-components'
import LinearProgress from '@material-ui/core/LinearProgress'

const CarouselBody = styled.aside`
  position: relative;
  width: 100%;
  height: 100%;

  &:before {
    content: 'Advertisements';
    top: -10px;
    position: absolute;
    color: #777;
    font-size: 13px;
    text-transform: uppercase
  }
`

const CarouselSlide = styled.div`
  background-color: ${props => props.background};
  text-align: center;
  display: ${props => props.visible === 1 ? 'flex' : 'none'};
  align-items: center;
  width: 100%;
  height: 100%;
  justify-content: center;
  transition: opacity 250ms;
  opacity: ${props => props.visible}
`

export default class Carousel extends Component {
  constructor(props) {
    super(props)
    this.state = { ads: undefined }
    this.changeSlide = this.changeSlide.bind(this)
  }

  componentDidMount() {
    fetch('http://localhost:3001/ads')
      .then(res => res.json())
      .then(json => this.setState({ adsData: json.data, ads: json.ads }))
      .then(this.setState({ error: undefined }))

    this.setState((state) => { return {
      currentSlide: 1
    }})

    setInterval(this.changeSlide, 4500)
  }

  changeSlide() {
    this.setState((state) => {
      return { currentSlide: state.currentSlide !== state.ads ? state.currentSlide + 1 : 1 }
    })
  }

  render() {
    return this.state.adsData === undefined ? (
      <LinearProgress />
    ) : (
      <CarouselBody>
        {this.state.ads === 0 ? <CarouselSlide visible={1}>There are no ads added!</CarouselSlide> : this.state.adsData.map(ad => <CarouselSlide key={ad.id} visible={this.state.currentSlide === ad.id ? 1 : 0}>{ad.text}</CarouselSlide>)}
      </CarouselBody>
    )
  }
}

那怎么办?请给我一些建议,我想说清楚,但不要像现在这样困难-没有任何动画。谢谢!

0 个答案:

没有答案