【问题标题】:Initial animation on react-spring not workingreact-spring 的初始动画不起作用
【发布时间】:2022-01-25 15:15:09
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: reactjs react-spring


    【解决方案1】:

    查看更多示例后,我意识到我将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 以防万一有人也在尝试使用弹簧制作动画手风琴/折叠。

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 2019-10-03
      • 2019-08-08
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多