将功能组件传递给 Animated.createAnimatedComponent

Ilj*_*lja 5 reactjs react-native react-hooks

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

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

来自使用 react hooks 的应用程序,基本上我的所有组件都可以使用。

有没有一种方法/帮助程序可以允许将这些传递给createAnimatedComponent而不将它们包裹起来,Animated.View甚至只是将它们包裹起来View

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

MJ *_*dio 7

这个 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);
}
Run Code Online (Sandbox Code Playgroud)

用法

export const AnimatedGradientButton = withAnimated(GradientButton);


小智 5

据我所知,您的选择是:

1)类组件的改变

2)将你的组件包装在一个View然后你可以制作动画的组件中

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

4)也许与此类似的解决方案更适合您。useRef和的组合useEffect