首页 > 解决方案 > 如何在 HOC 中使用 React Spring?

问题描述

我确信这与我不完全了解 React Spring 的工作原理或 HOC 的原理有关。

我正在尝试为 React 创建一个添加 React Spring 动画的 HOC(从左侧滑入子组件)

const SlideLeft = WrappedComponent => {
  const [props] = useSpring({
    translateX: "0",
    from: { translateX: "1000vw" }
  });
  return (
    <animated.div style={props}>
      <WrappedComponent />
    </animated.div>
  );
};

然后,在另一个组件中,我有这个:

    <SlideLeft>
      <Categories />
    </SlideLeft>

我认为这会起作用,但我得到了错误:

TypeError: arr[Symbol.iterator] is not a function

我发现这个页面建议将其更改为 const 道具:

https://github.com/react-spring/react-spring/issues/616

但是,当我这样做时,我得到了错误:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `SlideLeft`.

所以我不太确定如何让 HOC 与 React Spring 一起工作。

任何信息都会很有启发性。

标签: reactjsreact-hooksreact-spring

解决方案


像这样定义包装器:

 export function SlideLeft(props) {
      const animationProps = useSpring({
        from: { transform: "translate3d(-100%,0,0)" },
        to: { transform: "translate3d(0%,0,0)" }
      });

      return <animated.div style={{ ...animationProps }}> {props.children} </animated.div>;
    }

并像这样从父组件调用:

  <SlideLeft>
    <yourComponent/>
  </SlideLeft>

请注意,在fromto对象中,我使用的是相同的unit,即percentage。使用相同的单位很重要。如果您使用不同的单位,或传递无单位的数字,它将不起作用。


推荐阅读