Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6290

How do I avoid repeating HoC code when it differs by type between Animated and non-Animated components?

$
0
0

I'm trying to find a way of making my HoC handle both Animated and non-Animated versions of View and Text.

Right now I have two pieces of code that are similar except for the typings because Animated.View and View are different.

/** * This wraps a view component so the styles are exposed. * @param Component component to wrap * @param options options for the HoC building * @typeParam Q the props for the wrapped component * @typeParam T type for ref attribute of the wrapped component * @typeParam O options for the HoC building * @returns A named exotic componentwith P props that accepts a ref */export function withStyled<Q extends Animated.AnimateProps<ViewProps>, O = {}>(Component: ComponentType<Q>, options?: O): NamedExoticComponent<PropsWithoutRef<StyleProps & Q> & RefAttributes<Animated.View>> {    function useWrapped(props: StyleProps & Q, ref: Ref<Animated.View>): ReactElement<Q> {        // the an unknown as Q here is an example, but P and Q can be different.        const componentProps: Q = props as unknown as Q;        return <Component {...componentProps} ref={ref} />;    }    const displayName = Component.displayName || Component.name || "AnonymousComponent";    useWrapped.displayName = displayName;    return forwardRef(useWrapped);}/** * This wraps a view component so the styles are exposed. * @param Component component to wrap * @param options options for the HoC building * @typeParam Q the props for the wrapped component * @typeParam T type for ref attribute of the wrapped component * @typeParam O options for the HoC building * @returns A named exotic componentwith P props that accepts a ref */export function withStyledNoAnimation<Q extends ViewProps, O = {}>(Component: ComponentType<Q>, options?: O): NamedExoticComponent<PropsWithoutRef<StyleProps & Q> & RefAttributes<View>> {    function useWrapped(props: StyleProps & Q, ref: Ref<View>): ReactElement<Q> {        // the an unknown as Q here is an example, but P and Q can be different.        const componentProps: Q = props as unknown as Q;        return <Component {...componentProps} ref={ref} />;    }    const displayName = Component.displayName || Component.name || "AnonymousComponent";    useWrapped.displayName = displayName;    return forwardRef(useWrapped);}

Viewing all articles
Browse latest Browse all 6290

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>