【问题标题】:Pass functional component to Animated.createAnimatedComponent将功能组件传递给 Animated.createAnimatedComponent
【发布时间】:2019-12-13 00:34:52
【问题描述】:

如果您尝试将功能性(非反应类)组件传递给Animated.createAnimatedComponent,它会抛出一个错误提示

无状态功能组件作为 createAnimatedComponent 的子级无效

来自一个使用反应钩子的应用程序,基本上我的所有组件都可以正常工作。

有没有一种方法/助手可以允许将这些传递给 createAnimatedComponent 而无需将它们包装在 Animated.View 甚至只是 View 中?

这是我想要制作动画的组件示例

function MyComponent({ someProp }) {
  const [counter, setCounter] = useState(0);

  return (
    <View>
      <Text>{counter}</Text>
    </View>
  );

}

【问题讨论】:

  • useState(0) 是什么?
  • @hongdevelop React Hooks.
  • @hongdevelop 这里有更多关于钩子的信息reactjs.org/docs/hooks-intro.html
  • 只从 React 函数组件调用 Hooks。不要从常规 JavaScript 函数中调用 Hooks。 (只有另一个有效的地方可以调用 Hooks——你自己的自定义 Hooks。
  • 他们说你必须自己做 Hooks。

标签: reactjs react-native react-hooks


【解决方案1】:

这个HOC怎么样

export function withAnimated(
  WrappedComponent: React.ComponentType<any>,
): ComponentType {
  const displayName =
    WrappedComponent.displayName || WrappedComponent.name || 'Component';

  class WithAnimated extends React.Component {
    static displayName = `WithAnimated(${displayName})`;

    render(): React.ReactNode {
      return <WrappedComponent {...this.props} />;
    }
  }

  return Animated.createAnimatedComponent(WithAnimated);
}

用法

export const AnimatedGradientButton = withAnimated(GradientButton);

【讨论】:

    【解决方案2】:

    据我所知,您的选择是:

    1) 改成类组件

    2) 将您的组件包装在 View 中,然后您可以对其进行动画处理

    3) 使用react-native-animatable(或类似于此提供的解决方案):检查 here 用于库和参考的组合

    4) 也许类似于this one 的解决方案更适合您。 useRefuseEffect 的组合。

    【讨论】:

    猜你喜欢
    • 2021-04-29
    • 2020-05-27
    • 2017-02-19
    • 2020-08-20
    • 2019-08-20
    • 2020-09-04
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多