0

当我按下按钮时,我正在尝试从/到另一个组件的动画。我正在使用useTransition来自react-spring. 这样做时,动画会起作用,但是,当动画进行时,我的身高会发生变化。

我尝试positionsanimated.div(from react-spring) 上放置不同的内容并在其上设置固定高度。但似乎没有任何效果。

// The state that keeps track on the current component
const [index, setIndex] = useState(0);

// My function that updates my state
const onClick = useCallback(() => setIndex(state => (state === 0 ? 1 : 0)), []);

// The transition I'm using
const transitions = useTransition(index, p => p, {
    from: {
        opacity: 0,
        transform: index === 0 ? "translate3d(-100%,0,0)" : "translate3d(100%,0,0)"
    },
    enter: { opacity: 1, transform: "translate3d(0%,0,0)" },
    leave: {
        opacity: 0,
        transform: index === 0 ? "translate3d(50%,0,0)" : "translate3d(-50%,0,0)"
    }
});

// My components
const pages = [
    ({ style }) => <animated.div style={style}>1</animated.div>,
    ({ style }) => <animated.div style={style}>2</animated.div>
]

// How I'm rendering out the component
{transitions.map(({ item, props, key }) => {
    const Page = pages[item];
    return <Page key={key} style={props} />;
})}

动画有效,但是高度发生了变化。我制作了一个小代码框,在这里演示它:https ://codesandbox.io/s/dry-thunder-ydkg8

但在我的实际代码中,我的身高是这样的:https ://youtu.be/7cGLOK7fCco

4

1 回答 1

0

您需要使用position:absolute这两个元素来避免这种转变(并position:relative在其中一个父容器上添加一个)-(请参阅更新的代码框):

const pages = [
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "red"
        }}
      >
        First page
      </animated.div>
    ),
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "blue"
        }}
      >
        Second page
      </animated.div>
    )
  ];

于 2019-05-29T08:57:34.490 回答