react-spring 上的初始动画不起作用

Initial animation on react-spring not working

我正在使用 react-spring 来制作打开和关闭显示一些文本的手风琴组件的过渡动画。使用文档中的 this 示例,我能够想出一个更简单的版本,为高度和不透明度创建过渡:

function CollapseListItem({ title, text }: CollapseItemType) {
  const [isOpen, setIsOpen] = useState(false);
  const [ref, { height: viewHeight }] = useMeasure();

  const { height, opacity } = useSpring({
    from: { height: 0, opacity: 0 },
    to: {
      height: isOpen ? viewHeight : 0,
      opacity: isOpen ? 1 : 0
    }
  });

  const toggleOpen = () => {
    setIsOpen(!isOpen);
  };

  return (
    <>
      <button onClick={toggleOpen}>
        {title} click to {isOpen ? "close" : "open"}
      </button>
      <animated.div
        ref={ref}
        style={{
          opacity,
          height: isOpen ? "auto" : height,
          overflow: "hidden"
        }}
      >
        {text}
      </animated.div>
    </>
  );
}

问题是只有当你关闭手风琴时才会显示高度过渡,当你打开手风琴时文本突然出现,但在代码中我似乎找不到为什么它只在关闭时有效,我试图硬编码一些 viewHeight 值,但我没有运气。

Here's a code sandbox of what I have

查看更多示例后,我意识到我将 ref 放在错误的组件上,此更改解决了问题:

function CollapseListItem({ title, text }: CollapseItemType) {
  const [isOpen, setIsOpen] = useState(false);
  const [ref, { height: viewHeight }] = useMeasure();

  const props = useSpring({
    height: isOpen ? viewHeight : 0,
    opacity: isOpen ? 1 : 0
  });

  const toggleOpen = () => {
    setIsOpen(!isOpen);
  };

  return (
    <>
      <button onClick={toggleOpen}>
        {title} click to {isOpen ? "close" : "open"}
      </button>
      <animated.div
        style={{
          ...props,
          overflow: "hidden"
        }}
      >
        <div ref={ref}>{text}</div>
      </animated.div>
    </>
  );
}

Here's the full solution 如果有人也在尝试使用 spring 构建动画手风琴/折叠。