1

我正在尝试使用每次用户在图像轮播中单击下一步时页面加载时最初使用的动画。

我试过使用类似这样的反应弹簧:

const springs = useSprings(cards.map(item => ({ opacity: item.opacity }))

但是我得到“TypeError:无法读取未定义的属性'0'”

这在使用 useSpring (非复数)时有效:

import React, { useState } from "react";
import { useSpring, animated } from "react-spring";
import "./App.css";

const cards = [
  "https://upload.wikimedia.org/wikipedia/en/f/f5/RWS_Tarot_08_Strength.jpg",
  "https://upload.wikimedia.org/wikipedia/en/5/53/RWS_Tarot_16_Tower.jpg",
  "https://upload.wikimedia.org/wikipedia/en/9/9b/RWS_Tarot_07_Chariot.jpg",
  "https://upload.wikimedia.org/wikipedia/en/d/db/RWS_Tarot_06_Lovers.jpg",
  "https://upload.wikimedia.org/wikipedia/en/d/de/RWS_Tarot_01_Magician.jpg"
];

export default function App() {
  const [count, setCount] = useState(0);

  const props = useSpring({
    opacity: 1,
    marginTop: 100,
    boxShadow: "0px 100px 20px 0px rgba(0,0,0,0.4)",
    from: { opacity: 0, marginTop: 10 }
  });

  const prevSlide = () => {
    let prevSlide = count - 1 < 0 ? cards.length - 1 : count - 1;
    setCount(prevSlide);
  };

  const nextSlide = () => {
    let nextSlide = count + 1 < cards.length ? count + 1 : 0;
    setCount(nextSlide);
  };

  return (
    <div>
      <div className="container">
        <animated.div style={props}>
          <img src={cards[count]} alt="carousel-img" />
        </animated.div>
      </div>
      <div className="carousel__prev" onClick={prevSlide}>
        ◀︎
      </div>
      <div className="carousel__next" onClick={nextSlide}>
        ▶︎
      </div>
    </div>
  );
}

单击下一步时,如何使动画从顶部淡入图像?

4

1 回答 1

2

我认为对于轮播,useTransition 函数比 useSprings 更好。您可以使用 useTransition 定义进入和离开动画。当您按下下一个按钮时,上一个和下一个图像必须重叠,所以我将位置更改为绝对位置。页面布局以这种方式发生了一些变化。你必须修复它。

export default function App() {
  const [count, setCount] = useState(0);

  const transitions = useTransition([count], item => item, {
    from: { opacity: 0, marginTop: 10, position: 'absolute', boxShadow: "0px 100px 20px 0px rgba(0,0,0,0.4)" },
    enter: { opacity: 1, marginTop: 50},
    leave: {opacity: 0, marginTop: 100}
  });

  const prevSlide = () => {
    let prevSlide = count - 1 < 0 ? cards.length - 1 : count - 1;
    setCount(prevSlide);
  };

  const nextSlide = () => {
    let nextSlide = count + 1 < cards.length ? count + 1 : 0;
    setCount(nextSlide);
  };

  return (
    <div>
      <div className="container">
        {transitions.map(({item, props, key}) => (
          <animated.div key={key} style={props}>
          {item}
            <img src={cards[item]} alt="carousel-img" />

          </animated.div>
        ))}

      </div>
      <div className="carousel__prev" onClick={prevSlide}>
        ◀︎
      </div>
      <div className="carousel__next" onClick={nextSlide}>
        ▶︎
      </div>
    </div>
  );
}

这是一个 codeSandbox 示例:https ://codesandbox.io/s/image-carousel-with-react-spring-usetransition-q1ndd

在codesandbox示例中我还引入了一个反向状态,因为如果我用prev按钮更改动画感觉会更好。

于 2019-07-04T06:29:16.167 回答