当 ViewPager 移动到下一张幻灯片时,上一张幻灯片应该减少每次移动的不透明度值

When ViewPager move to next slide then previous slide should decrease opacity value for every move

我的要求是当ViewPager click and drag image for next image then previous image should decrease opacity for every drag. This is my codesandbox代码。

这张图片是我的要求的小例子。

import React, { useRef } from 'react'
import clamp from 'lodash-es/clamp'
import { useSprings, animated } from 'react-spring'
import { useDrag } from 'react-use-gesture'
import './styles.css'

function Viewpager() {
  const index = useRef(0)

  const [props, set] = useSprings(alphabets.length, i => ({
    x: i * window.innerWidth,
    scale: 1,
    opacity: 1,
    display: 'block'
  }))
  const bind = useDrag(({ active, down, movement: [mx], direction: [xDir], distance, cancel }) => {
    set(i => {
      if (i < index.current - 1 || i > index.current + 1) return { display: 'none' }
      const x = (i - index.current) * window.innerWidth + (down ? mx : 0)
      const scale = down ? 1 - distance / window.innerWidth / 2 : 1
      const opacity = active ? distance * 0.01 : 1
      return { x, scale, opacity, display: 'block' }
    })
  })

  return props.map(({ x, display, scale, opacity }, i) => (
    <animated.div
      {...bind()}
      key={i}
      style={{
        opacity,
        display,
        x
      }}
    />
  ))
}

我需要与 codesandbox 代码相同的功能,并在将卡片拖到其他卡片时并行降低不透明度。如果有人在其他库中有任何其他解决方案,例如 framer-motion。这也很有帮助。

您应该将 x 值插入到不透明度中。 x值在0到负innerWitdh / 2之间。你应该将它转移到1到0之间的值。

这是工作公式。

opacity: x.to(x => 1 + x / (window.innerWidth / 2)),

示例如下: https://codesandbox.io/s/card-slider-jwf3f

旁注:

如果将公式显示在屏幕上,您可以很容易地检查它。您所要做的就是将其作为 animated.div 的文本。例如:

 <animated.div>{x.to(x => 1 - Math.abs(x / (window.innerWidth / 2)))}</animated.div>