react-native-linear-gradient兼容问题

背景

react-native-linear-gradient

可能因为react-native版本过低问题,导致无法支持react-native-linear-gradient,所以需要进行兼容处理。

requireNativeComponent: “BVLinearGradient” was not found in the UIManager.

代码

Utils.ts:

import { NativeModules } from 'react-native';

export function isNativeComponentExisted(componentName: string): boolean {
  return (
    NativeModules.UIManager &&
    NativeModules.UIManager.hasOwnProperty(componentName) // here
  );
}

MyLibraryGradient.tsx:

import * as React from 'react';
import { View } from 'react-native';
import LibraryGradient, {
  LinearGradientProps,
} from 'react-native-linear-gradient';
import { isNativeComponentExisted } from './Utils';

/**
 * @name LinearGradient
 * @desc Check {@link https://github.com/react-native-community/react-native-linear-gradient#additional-props react-native-linear-gradient} for configuration details
 * @param {Object} LinearGradientProps
 */
const RNLinearGradient = (props: LinearGradientProps) => {
  const useCompat = !isNativeComponentExisted('BVLinearGradient');
  if (useCompat) {
    const { start: _, end: __, colors: ___, locations: ____, ...rest } = props; // 排除start,end等属性,这些属性对于View组件是不对的
    return (
      <View
        {...rest}
        style={[props.style, { backgroundColor: props.colors[1] as string }]}
      />
    );
  }
  return <LibraryGradient {...props} />;
};

export default RNLinearGradient;