【问题标题】:How to use React Spring in a HOC?如何在 HOC 中使用 React Spring?
【发布时间】:2019-12-28 23:44:03
【问题描述】:

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

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

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 props:

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 一起工作。

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

【问题讨论】:

    标签: reactjs react-hooks react-spring


    【解决方案1】:

    像这样定义包装器:

     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。使用相同的单位很重要。如果您使用不同的单位,或传递无单位的数字,它将不起作用。

    【讨论】:

    • 那你不能用 const 吗?
    • @CecilRodriguez 函数定义中的常量?你可以像这样:const SlideLeft = (props) =&gt; { ....
    猜你喜欢
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2019-05-09
    • 2019-01-07
    • 2020-04-30
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多