首页 > 解决方案 > 使用 react-spring 在 react-use-gesture 中设置初始值

问题描述

我只是通过一些例子来学习 react-spring 和 react-use-gesture 。我不知道如何设置和存储 useSprings 的道具。试图设置初始值,所以它基本上是一个拖放。我意识到还有其他方法可以实现拖放,我正试图将我的注意力集中在 react-spring 上,这样我就可以开始构建其他东西了。

无论如何,使用该函数设置初始值会返回一个错误,即 pos 未定义。这是我的代码:

    const [ props , set] = useSprings(4,(i) => ({ pos: [i*10, i*10] }))
  
    const bind = useDrag(
      ({ args: [index], down, movement: pos }) => {
        set((i) => {
            if (index !== i) return
            return { pos, immediate: down }
          })
      },
          { initial: () => pos.getValue() }
    )
    return props.map(({ pos }, i) => (
        <animated.div
        key={i}
      className="Rocket"
        {...bind(i)}
        style={{ transform: interpolate([pos], ([x, y]) => `translate3d(${x}px,${y}px,0)`) }}
      />
    ))
  }

如果我只有一个并使用 useSpring,我可以直接从钩子中设置初始值:

    const [{ pos }, setPos] = useSpring(() => ({ pos: [0, 0] }))
  
    const bind = useDrag(
      ({ down, movement: pos }) => {
        setPos({ pos, immediate: down })
      },
      { initial: () => pos.getValue() }
    )
    return (
      <animated.div
      className="Rocket"
        {...bind()}
        style={{ transform: interpolate([pos], ([x, y]) => `translate3d(${x}px,${y}px,0)`) }}
      />
    )
  }

我似乎无法追踪它。我有点同时学习钩子,所以我对钩子的存储方式和位置的理解可能是我的问题。非常感谢任何见解。

标签: reactjsreact-spring

解决方案


推荐阅读