通过将redux状态传递给react中的动态react-pose道具来移动div

问题描述:

我已将这个小沙盒拼凑起来以演示: https://codesandbox.io/s/64xv97y45n

I've cobbled together this little sandbox to demonstrate: https://codesandbox.io/s/64xv97y45n

应该在键入字母时移动左上角的紫色div。键入字母后,redux存储上的currIndex(当前活动的框)值将相应地增加或减少。然后,reducer使用currIndex来计算currentCoords或div的新绝对位置(出于附加沙箱的目的,稍微偏右)。然后将currentCoords存储属性作为道具传递,以控制紫色div的动态姿势。但是div拒绝更新其姿势。 Redux DevTools告诉我currentCoords正在正确更新,或者至少更新得足够好,可以稍稍移动一下。

The purple div in the upper left hand corner is supposed to move as letters are typed. When a letter is typed, the currIndex (the currently active box) value on the redux store is incremented or decremented accordingly. The reducer then uses currIndex to compute the currentCoords or the div's new absolute position (for the purposes of attached sandbox, 'slightly more to the right'). The currentCoords store property is then passed on as a prop to control the dynamic pose of the purple div. But the div refuses to update its pose. Redux DevTools tells me currentCoords is updating properly, or at least well enough for it to move a little. What gives?

相关逻辑:

 const reducer = (state = initState, action) => {
      switch (action.type) {
        case "KEYPRESS":
          return {
            ...state,
            number: [...state.number, action.key],
            currIndex: ++state.currIndex,
            currentCoords: state.boxCoords[state.currIndex]
          };

<SNIP>

const Cursor = posed.div({
  visible: {
    opacity: 1,
    x: ({ xPos }) => xPos,
    y: ({ yPos }) => yPos
  },

  hidden: {
    opacity: 0
  }
});

<SNIP>



<Cursor
            className="cursor"
            initialPose="visible"
            xPos={this.props.currentCoords.x}
            yPos={this.props.currentCoords.y}
          />


如果要转换 posed 元素,而不更改当前的 pose ,您需要传递 poseKey 来做出反应。同样根据 initialPose 属性的文档:

If you want to transition your posed element without changing the current pose you need to pass a poseKey to react on. Also according to documentation of initialPose property:


一旦安装了组件,它将从这个姿势转换成姿势

这就是为什么必须通过 pose 属性设置为 posed 组件,否则将重置 initialPose 。因此,基本上< Cursor> 组件应如下所示:

That is why have must pass pose property to the posed component otherwise initialPose will be reset. So basically <Cursor> component should be rendered like this:

<Cursor
   className="cursor"
   initialPose="visible"
   pose="visible"                        // you can hold the pose in your state and use it here like this.state.pose
   poseKey={this.props.currentCoords.x}
   xPos={this.props.currentCoords.x}
   yPos={this.props.currentCoords.y}
/>